iOS開發多線程篇—線程的狀態,ios開發多線程
iOS開發多線程篇—線程的狀態
一、簡單介紹
線程的建立:
self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];
說明:建立線程有多種方式,這裡不做過多的介紹。
線程的開啟:
[self.thread start];
線程的運行和阻塞:
(1)設定線程阻塞1,阻塞2秒
[NSThread sleepForTimeInterval:2.0];
(2)第二種設定線程阻塞2,以目前時間為基準阻塞4秒
NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];
[NSThread sleepUntilDate:date];
線程處理阻塞狀態時在記憶體中的表現情況:(線程被移出可調度線程池,此時不可調度)
線程的死亡:
當線程的任務結束,發生異常,或者是強制退出這三種情況會導致線程的死亡。
線程死亡後,線程對象從記憶體中移除。
二、程式碼範例
程式碼範例1:
1 // 2 // YYViewController.m 3 // 04-NSThread02-線程的狀態 4 // 5 // Created by apple on 14-6-23. 6 // Copyright (c) 2014年 itcase. All rights reserved. 7 // 8 9 #import "YYViewController.h"10 11 @interface YYViewController ()12 @property(nonatomic,strong)NSThread *thread;13 14 @end15 16 @implementation YYViewController17 18 - (void)viewDidLoad19 {20 [super viewDidLoad];21 22 //建立線程23 self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];24 //設定線程的名稱25 [self.thread setName:@"線程A"];26 }27 //當手指按下的時候,開啟線程28 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event29 {30 //開啟線程31 [self.thread start];32 }33 34 -(void)test35 {36 //擷取線程37 NSThread *current=[NSThread currentThread];38 NSLog(@"test---列印線程---%@",self.thread.name);39 NSLog(@"test---線程開始---%@",current.name);40 41 //設定線程阻塞1,阻塞2秒42 NSLog(@"接下來,線程阻塞2秒");43 [NSThread sleepForTimeInterval:2.0];44 45 //第二種設定線程阻塞2,以目前時間為基準阻塞4秒46 NSLog(@"接下來,線程阻塞4秒");47 NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];48 [NSThread sleepUntilDate:date];49 for (int i=0; i<20; i++) {50 NSLog(@"線程--%d--%@",i,current.name);51 52 }53 NSLog(@"test---線程結束---%@",current.name);54 }55 56 @end
列印查看:
程式碼範例2(退出線程):
1 // 2 // YYViewController.m 3 // 04-NSThread02-線程的狀態 4 // 5 // Created by apple on 14-6-23. 6 // Copyright (c) 2014年 itcase. All rights reserved. 7 // 8 9 #import "YYViewController.h"10 11 @interface YYViewController ()12 @property(nonatomic,strong)NSThread *thread;13 14 @end15 16 @implementation YYViewController17 18 - (void)viewDidLoad19 {20 [super viewDidLoad];21 22 //建立線程23 self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];24 //設定線程的名稱25 [self.thread setName:@"線程A"];26 }27 //當手指按下的時候,開啟線程28 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event29 {30 //開啟線程31 [self.thread start];32 }33 34 -(void)test35 {36 //擷取線程37 NSThread *current=[NSThread currentThread];38 NSLog(@"test---列印線程---%@",self.thread.name);39 NSLog(@"test---線程開始---%@",current.name);40 41 //設定線程阻塞1,阻塞2秒42 NSLog(@"接下來,線程阻塞2秒");43 [NSThread sleepForTimeInterval:2.0];44 45 //第二種設定線程阻塞2,以目前時間為基準阻塞4秒46 NSLog(@"接下來,線程阻塞4秒");47 NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];48 [NSThread sleepUntilDate:date];49 for (int i=0; i<20; i++) {50 NSLog(@"線程--%d--%@",i,current.name);51 if (5==i) {52 //結束線程53 [NSThread exit];54 }55 56 }57 NSLog(@"test---線程結束---%@",current.name);58 }59 60 @end
列印樣本:
注意:人死不能複生,線程死了也不能複生(重新開啟),如果線上程死亡之後,再次點擊螢幕嘗試重新開啟線程,則程式會掛。