国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > iOS > 正文

iOS多線程開發(fā)――NSThread淺析

2020-07-26 03:20:55
字體:
供稿:網(wǎng)友

  在iOS開發(fā)中,多線程的實現(xiàn)方式主要有三種,NSThread、NSOperation和GCD,我前面博客中對NSOperation和GCD有了較為詳細的實現(xiàn),為了學習的完整性,今天我們主要從代碼層面來實現(xiàn)NSThread的使用。案例代碼上傳至 https://github.com/chenyufeng1991/NSThread。

(1)初始化并啟動一個線程

  - (void)viewWillAppear:(BOOL)animated  {  [super viewWillAppear:animated];  //獲取當前線程  NSThread *current = [NSThread currentThread];  NSLog(@"當前線程為 %@",current);  //初始化線程  NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  //設(shè)置線程的優(yōu)先級(0.0-1.0)  thread.threadPriority = 1.0;  thread.name = @"新線程1";  [thread start];  }  - (void)run  {  NSLog(@"線程執(zhí)行");  //獲取當前線程  NSThread *current = [NSThread currentThread];  NSLog(@"當前線程為 %@",current);  //線程休眠,可以模擬耗時操作  [NSThread sleepForTimeInterval:2];  //獲取主線程  NSThread *mainThread = [NSThread mainThread];  NSLog(@"子線程中獲得主線程 %@",mainThread);  }

  其中currentThread,這個方法很有用,常常可以用來判斷某方法的執(zhí)行是在哪個線程中。

  (2)NSThread可以指定讓某個線程在后臺執(zhí)行:

  //后臺創(chuàng)建一個線程來執(zhí)行任務(wù),需要在調(diào)用的方法中使用自動釋放池  [self performSelectorInBackground:@selector(run3) withObject:nil];

  - (void)run3  {  @autoreleasepool {  NSLog(@"主線程3:%@,當前線程3:%@",[NSThread mainThread],[NSThread currentThread]);  }  }

(3)子線程執(zhí)行耗時操作,主線程更新UI。這是多線程開發(fā)中最常用的案例。子線程中調(diào)用performSelectorOnMainThread方法用來更新主線程。

//測試在子線程中調(diào)用主線程更新UI- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; NSThread *subThread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; //NSThread可以控制線程開始 [subThread start];}- (void)run{ NSLog(@"主線程1:%@,當前線程1:%@",[NSThread mainThread],[NSThread currentThread]); //以下方法需要在子線程中調(diào)用 [self performSelectorOnMainThread:@selector(invocationMainThread) withObject:nil waitUntilDone:YES];}- (void)invocationMainThread{ NSLog(@"主線程2:%@,當前線程2:%@",[NSThread mainThread],[NSThread currentThread]); NSLog(@"調(diào)用主線程更新UI");}

  (4)同樣,我們也可以新建一個子線程的類,繼承自NSThread. 然后重寫里面的main方法,main方法就是該線程啟動時會執(zhí)行的方法。

@implementation MyThread- (void)main{ NSLog(@"main方法執(zhí)行");}@end

  然后按正常的創(chuàng)建啟動即可。線程就會自動去執(zhí)行main方法。

//可以自己寫一個子類,繼承自NSThread,需要重寫main方法/** * 執(zhí)行的代碼是在main中的,而不是使用@selector. 使用main方法,線程中執(zhí)行的方法是屬于對象本身的,這樣可以在任何其他需要使用這個線程方法的地方使用,而不用再一次實現(xiàn)某個方法。  而其他的直接NSThread的創(chuàng)建線程,線程內(nèi)執(zhí)行的方法都是在當前的類文件里面的。 */- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; MyThread *thread = [[MyThread alloc] init]; [thread start];}

  (5)NSThread中還有一個很常用的方法就是延遲。延遲2s執(zhí)行。

 //線程休眠,可以模擬耗時操作 [NSThread sleepForTimeInterval:2];

   對于多線程的三種實現(xiàn)方式,我們都要能夠熟練使用

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 衡阳县| 九台市| 仲巴县| 绥化市| 龙游县| 建德市| 洛宁县| 新乡市| 延边| 沛县| 柳江县| 阿勒泰市| 衡东县| 陈巴尔虎旗| 麻城市| 吉林市| 龙门县| 抚顺市| 垦利县| 湛江市| 吉水县| 闸北区| 明星| 武川县| 改则县| 西乌| 嘉兴市| 息烽县| 新闻| 论坛| 龙胜| 资源县| 淄博市| 高碑店市| 扎鲁特旗| 太原市| 卢龙县| 汶上县| 洛南县| 冷水江市| 镇赉县|