iOS多线程初见
1 1. 三种创建线程的方法 2 3 //第一种 4 5 NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doAction) object:nil]; 6 7 //线程名 8 9 thread1.name = @"thread1"; 10 11 //线程优先级,0 ~ 1 12 13 thread1.threadPriority = 1.0; 14 15 //开启线程 16 17 [thread1 start]; 18 19 //第二种 20 21 //通过类方法创建线程,不用显示的开启start 22 23 [NSThread detachNewThreadSelector:@selector(doAction) toTarget:self withObject:nil]; 24 25 //第三种 26 27 //隐式创建多线程 28 29 [self performSelectorInBackground:@selector(doAction:) withObject:nil]; 30 31 32 33 34 35 @implementation ViewController 36 37 - (void)viewDidLoad { 38 39 [super viewDidLoad]; 40 41 // Do any additional setup after loading the view, typically from a nib. 42 43 44 45 46 47 NSLog(@"mainThread - %@",[NSThread mainThread]); 48 49 50 51 NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(handleAction) object:nil]; 52 53 54 55 //就绪状态 56 57 [thread start]; 58 59 } 60 61 62 63 - (void)handleAction { 64 65 66 67 for (NSInteger i = 0 ; i < 100; i ++) { 68 69 70 71 //阻塞状态 72 73 // [NSThread sleepForTimeInterval:2]; 74 75 // [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]]; 76 77 78 79 // NSLog(@"%@,%@",[NSThread currentThread],@(i)); 80 81 //可以在子线程获取主线程 82 83 NSLog(@"mainThread - %@",[NSThread mainThread]); 84 85 if (i == 10) { 86 87 //退出 88 89 [NSThread exit]; 90 91 } 92 93 } 94 95 } 96 97 3.同步代码块实现买票功能 98 99 @implementation ViewController 100 101 102 103 - (void)viewDidLoad { 104 105 [super viewDidLoad]; 106 107 // Do any additional setup after loading the view, typically from a nib. 108 109 110 111 self.tickets = 20; 112 113 114 115 NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; 116 117 // thread1.name = @"computer"; 118 119 120 121 [thread1 start]; 122 123 124 125 126 127 NSThread * thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; 128 129 // thread2.name = @"phone"; 130 131 132 133 [thread2 start]; 134 135 } 136 137 138 139 - (void)saleTicket { 140 141 142 143 144 145 while (1) { 146 147 148 149 // [NSThread sleepForTimeInterval:1]; 150 151 152 153 154 155 //token必须所有线程都能访问到,一般用self 156 157 158 159 // @synchronized() { 160 161 162 163 //代码段 164 165 // } 166 167 168 169 170 171 // NSObject * o = [[NSObject alloc] init]; 172 173 174 175 //互斥锁 176 177 @synchronized(self) { 178 179 180 181 [NSThread sleepForTimeInterval:2]; 182 183 184 185 if (self.tickets > 0) { 186 187 188 189 NSLog(@"%@ 还有余票 %@ 张",[NSThread currentThread],@(self.tickets)); 190 191 192 193 self.tickets -- ; 194 195 196 197 } else { 198 199 200 201 NSLog(@"票卖完了"); 202 203 204 205 break; 206 207 } 208 209 210 211 } 212 213 214 215 } 216 217 218 219 } 220 221