杀死一个线程

ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run1) object:nil];
[ticketsThreadone setName:@"Thread-1"];
[ticketsThreadone start];

ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run2) object:nil];
[ticketsThreadtwo setName:@"Thread-2"];
[ticketsThreadtwo start];


- (void)run1{
while (YES) {
[NSThread sleepForTimeInterval:1];
NSLog(@"当前数是:%d,线程名:%@",count,[[NSThread currentThread] name]);
count++;
if (count == 10) {
[ticketsThreadtwo cancel];
}
}
}
- (void)run2{
while (YES) {
if ([[NSThread currentThread] isCancelled]) {
[NSThread exit];
}
[NSThread sleepForTimeInterval:1];
NSLog(@"当前数是:%d,线程名:%@",count,[[NSThread currentThread] name]);
count++;
}
}

如果有什么不明白再交流

 

感想: while(true)  + if...else 组合 其实就相当于 for  循环。  所以说,for 循环可以被拆分成while   if  用于 多线程。

- (void)run{  
    while (TRUE) {  
        // 上锁  
        [ticketsCondition lock];  
        [ticketsCondition wait];  
        [theLock lock];  
        if(tickets >= 0){  
            [NSThread sleepForTimeInterval:0.09];  
            count = 100 - tickets;  
            NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);  
            tickets--;  
        }else{  
            break;  
        }  
        [theLock unlock];  
        [ticketsCondition unlock];  
    }  

 

 

 

 

posted @ 2013-05-27 22:46  ygm900  阅读(1306)  评论(0编辑  收藏  举报