用NSThread,如何启动,阻塞,关闭线程

Posted on 2016-07-16 17:33  柠檬片  阅读(465)  评论(0)    收藏  举报

 1 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     //创建线程
 4     NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run2) object:nil];
 5     //启动线程
 6     [thread start];
 7 }
 8 
 9 -(void)run2
10 {
11     for (NSInteger i=0; i<100; i++) {
12         NSLog(@"%@--%zd",[NSThread currentThread],i);
13         if (50 == i) {
14             //死亡
15 //            [NSThread exit];
16 //            return;
17             
18             break;
19         }
20     }
21 }
22 -(void)run
23 {
24     NSLog(@"-----");
25     //阻塞线程
26 //    [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
27     
28     [NSThread sleepForTimeInterval:3.0];
29 //    NSLog(@"%@",[NSDate distantFuture]);
30     
31 //    [NSThread sleepForTimeInterval:3.0];
32 //    [NSThread sleepUntilDate:[NSDate distantFuture]];
33 //    [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];
34     NSLog(@"+++++++");
35 }
View Code