1 // 2 // ViewController.m 3 // 00-NSThread(四种方式) 4 // 5 // Created by mac on 16/4/20. 6 // Copyright © 2016年 mac. All rights reserved. 7 // 8 #import "CustumOperation.h" 9 #import "ViewController.h" 10 11 @interface ViewController () 12 13 @end 14 15 @implementation ViewController 16 /** 17 * 线程优先级是系统自动分配的,随机分配 18 */ 19 20 - (void)viewDidLoad { 21 [super viewDidLoad]; 22 23 [self createdThread1]; 24 [self createdThread2]; 25 [self createdThread3]; 26 [self createdThread4]; 27 } 28 29 /** 30 * 创建多线程方法一 31 */ 32 - (void)createdThread1 { 33 34 //1.创建多线程方法(一)NSThread 35 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil]; 36 thread.name = @"thread1111"; 37 38 //启动多线程 39 [thread start]; 40 41 //延迟调用cancel方法取消线程 42 [self performSelector:@selector(cancelThread:) withObject:thread afterDelay:0.2]; 43 44 //打印主线程 45 NSLog(@"%d===main:%@==%lf", [NSThread isMainThread],[NSThread currentThread], [NSThread threadPriority]); 46 } 47 - (void)threadAction { 48 49 //3)休眠 50 [NSThread sleepForTimeInterval:2]; 51 52 if ([[NSThread currentThread] isCancelled]) { 53 54 NSLog(@"当前线程退出"); 55 56 //2)退出线程 57 [NSThread exit]; 58 } 59 60 for (int i = 0; i < 50; i ++) { 61 62 NSLog(@"%@", [NSThread currentThread]); 63 } 64 65 NSLog(@"%lf,%d", [NSThread threadPriority], [NSThread isMainThread]); 66 } 67 - (void)cancelThread:(NSThread *)thread { 68 69 //1)标记线程状态为:即将取消并非真正已经取消了 70 [thread cancel]; 71 } 72 73 /** 74 * 创建多线程方法二 75 */ 76 - (void)createdThread2 { 77 78 [NSThread detachNewThreadSelector:@selector(threadAction) toTarget:self withObject:nil]; 79 } 80 /** 81 * 创建多线程方法三 82 */ 83 - (void)createdThread3 { 84 85 [self performSelectorInBackground:@selector(threadAction) withObject:nil]; 86 } 87 /** 88 * 创建多线程方法四 89 */ 90 - (void)createdThread4 { 91 92 CustumOperation *custum = [[CustumOperation alloc] init]; 93 94 //start和main的区别: main只会调用方法不会开启新的线程 95 [custum start]; 96 // [custum main]; 97 } 98 99 100 101 @end