iOS —— 多線程NSThread

來源:互聯網
上載者:User

標籤:int   target   思考   控制台   nslog   create   get   text   時間   

一、NSThread 1. 介紹

iOS 中的線程對象,將一個線程封裝為一個 OC 對象,可以設定線程名、優先順序等屬性

 

2. 常用方法

 

二、樣本1. 建立線程
// 1. 獲得主線程NSThread * mainThread = [NSThread mainThread];    NSLog(@"main --- %@", mainThread);    // 2. 獲得當前線程(也就是主線程)NSThread * currentThread = [NSThread currentThread];    NSLog(@"current --- %@", currentThread);// 3. 方式一建立線程[self createNSThread1];    // 4. 方式二建立線程//[self createNSThread2];    // 5. 方式三建立線程//[self createNSThread3];
 1 - (void)createNSThread1 { 2  3     // 1. 建立線程對象, 並指定線程啟動並執行方法 4     NSThread * newThread = [[NSThread alloc] initWithTarget:self selector:@selector(runNSThread:) object:@"手動開啟新線程"]; 5      6     // 設定線程名稱 7     [newThread setName:@"線程A"]; 8      9     // 開啟線程,只有開啟線程時,該線程才會運行10     [newThread start];11 12 }
 1 - (void)runNSThread:(NSString *)str { 2  3     // 1. 擷取當前線程 4     NSThread * currentThread = [NSThread currentThread]; 5      6     NSLog(@"current --- %@", currentThread); 7      8     // 2. 執行耗時 9     for (int i = 0; i < 10; ++i) {10     11         NSLog(@"%i --- %@ --- %@", i, currentThread, str);12     13     }14 15 }

運行結果

可以看出,用 NSThread 的 initWithTarget: selector: objecg: 方法建立了一個新的進程對象(81783),並通過 start 開啟該進程

 

1 - (void)createNSThread2 {2 3     // 1. 自動建立新的線程並開啟,此方法無需手動調用 start 方法開啟進程,會自動開啟4     [NSThread detachNewThreadSelector:@selector(runNSThread:) toTarget:self withObject:@"自動開啟新線程1"];5 6 }

運行結果和上述類似,只不過新建立的進程 ID 和 線程 ID 不相同,這裡就不再放圖了

 

1 - (void)createNSThread3 {2     3     // 1. 自動建立新的線程並開啟4     [self performSelectorInBackground:@selector(runNSThread:) withObject:@"自動開啟新線程1"];5     6 }

運行結果和上述類似,只不過新建立的進程 ID 和 線程 ID 不相同,這裡就不再放圖了

 

2. 阻塞主線程

在 xib 中拖入一個 UITextField 控制項 和 UIButton 控制項,並將 UIButton 建立一個 IBAction 的動作方法;代碼如下

 1 - (IBAction)btn1Click:(id)sender { 2  3     // 1. 擷取當前線程 4     NSThread * thread = [NSThread currentThread]; 5      6     // 2. 使用 for 進行一些延時操作 7     for (int i = 0; i < 50000; ++i) { 8      9         NSLog(@"%i --- %@", i, thread);10     11     }18 19 }

 

運行程式,會發現在控制台一直會輸出 for 語句的內容,而此時點擊 UITextField 控制項是無法彈出鍵盤的

原因是 : 此時只有一個線程,即主線程,而主線程是以串列的方式啟動並執行,由於當前 for 語句的耗時較多,需要一定的時間才可以執行完,所以在執行完 for 語句的耗時任務之前,是不可以執行其他的任務的;

 

思考 : 如果將建立線程的程式裡的 for 語句的 i < 10 改為 i < 50000,那麼在運行程式時,是否可以點擊 UITextField 以響應

從圖可以看出,執行耗時任務的是子線程而非主線程,而響應控制項事件的是主線程;主線程建立了子線程後,就將耗時任務交給它執行,所以主線程此時就可以響應控制項的事件了

iOS —— 多線程NSThread

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.