天天看點

ios - 多線程之三:NSThread

NSThread 線程解決方案是經過蘋果封裝後的,并且是完全面向對象的,基于此呢,我們就可以直接來操作線程對象,比較直覺。

思路

在viewController中添加一個按鈕,點選按鈕執行 NSThread 線程管理。

代碼示範

1:建立按鈕

//第二種方式 NSThread

  UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];

btn1.frame = CGRectMake(40, 150, 100, 40);

[btn1 setTitle:@"NSThread" forState:UIControlStateNormal];

[btn1 setBackgroundColor:[UIColor blueColor]];

[btn1 addTarget:self action:@selector(click_NSThread) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn1];
           

2:定義點選事件

知識點:

- 初始化方法(有三種):

1:alloc - init 方法,使用該方法建立的線程需要手動開啟線程 start。

2:類方法,靜态方法:detachNewThreadSelector 建立并且執行

3:NSObject的内置方法:performSelectorInBackground,當然NSObject還有其他進行切換的方法:performSelectorOnMainThread(回到主線程中執行)performSelector:<@selector> onThread: ,

三種方式的優缺點對比

方式 優點 缺點
alloc - init 方法 有自己的對象,可管理;可以設定線程名稱,友善線程追蹤; 需要調用start才能夠執行
靜态方法 沒有線程對象;無需編寫執行語句 無法設定線程名稱;無法設定線程優先級;
NSObject的内置方法 沒有線程對象;無需編寫執行語句 無法設定線程名稱;無法設定線程優先級;

- 線程名稱:類似ID,可在程式的調試過程中發揮很大作用;

- 線程優先級;大部分的了解還是我如果優先級大,就一定會先執行完,這個是一種誤讀,設定優先級大在多線程的世界裡隻能是表示優先級大的任務執行的機率相對大點。

代碼:

- (void) click_NSThread {

NSLog(@”主線程列印”);

// 2 : NSThread 多線程

// 初始化方法一 : alloc - init 方法,使用該方法建立的線程需要手動開啟線程start

NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];

thread1.name = @”first_NSThread”; //設定線程的名稱

thread1.threadPriority = 1; //設定線程的執行優先級

//初始化方法二 : NSThread類方法建立, 不能指定線程名稱和優先級
//    [NSThread detachNewThreadSelector:@selector(runThread1) toTarget:self withObject:nil];

//初始化方法三 : NSObject的内置方法,不能指定線程名稱和優先級
//    [self performSelectorInBackground:@selector(runThread1) withObject:nil];


//設定線程的優先級
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];
thread2.name = @"second_NSThread";
thread2.threadPriority = 0.5;


    NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];
    thread3.name = @"third_NSThread";
    thread3.threadPriority = 0.2;

  [thread1 start]; //手動開啟線程
  [thread2 start];
  [thread3 start];
}