網路開始---多線程---NSThread-01-基本使用(瞭解)(二),------nsthread-01-
1 #import "HMViewController.h" 2 3 @interface HMViewController () 4 5 @end 6 7 @implementation HMViewController 8 9 - (void)viewDidLoad10 {11 [super viewDidLoad];12 // Do any additional setup after loading the view, typically from a nib.13 }14 15 //下載操作,16 - (void)download:(NSString *)url17 {18 NSLog(@"下載東西---%@---%@", url, [NSThread currentThread]);19 20 21 22 23 24 }25 26 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event27 {28 [self createThread3];29 }30 31 /**32 * 建立線程的方式333 隱式建立線程並自動啟動線程34 */35 - (void)createThread336 {37 // 這2個不會建立線程,在當前線程中執行38 // [self performSelector:@selector(download:) withObject:@"http://c.gif"];39 // [self download:@"http://c.gif"];40 41 //這個隱式建立線程,在後台會自動建立一條子線程並執行download方法,42 [self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];43 }44 45 /**46 * 建立線程的方式247 建立線程後自動啟動線程48 */49 - (void)createThread250 {51 //從當前線程中分離出一條新的線程52 [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];53 }54 55 /**56 * 建立線程的方式157 建立線程後不會自動啟動,需要寫一句啟動才會啟動線程58 這種建立線程的方法是3種當中最好的,可以對線程進行詳細的設定59 60 */61 - (void)createThread162 {63 // 建立線程64 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"];65 66 //線程的名字,列印線程的時候可以看到列印的線程的名字67 thread.name = @"下載線程";68 69 object://你開闢線程要執行的方法要傳的參數,比如這裡傳一個url,傳到download方法裡70 //這個參數是要從當前線程傳到子線程中去的71 72 // 啟動線程(調用self的download方法) 只有啟動線程才會調用self的download方法73 [thread start]; //必須有這一句才能啟動線程74 //並且執行過程是在子線程中執行的,就是新開闢的一條線程 把耗時操作成功放到子線程中去75 76 [NSThread mainThread];//獲得主線程77 NSThread *current=[NSThread currentThread];//獲得當前線程78 79 80 [thread isMainThread];//判斷當前線程(新建立線程)是否為主線程,返回Bool值81 [NSThread isMainThread];// 判斷當前執行代碼的方法是否在主線程,返回Bool值82 83 }84 85 @end