天天看點

Objective-c中線程NSThread的使用

NSThread使用

1.建立并啟動線程

thread = [[NSThread alloc]initWithTarget:self selector:@selector(startMonitor) object:nil];  
[thread start];       

2.停止線程

    先向線程發送cancel消息,将線程标記為停止,然後在合适的地方判斷線程是否标記為退出,如果是,則發送exit消息,真正退出線程

- (void)getInfo:(id)sender  
{    
    if (!running) {  
        NSLog(@"start monitor");  
        thread = [[NSThread alloc]initWithTarget:self selector:@selector(startMonitor) object:nil];  
        [thread start];  
        running = true;  
    }  
    else{  
        NSLog(@"stop monitor");  
        [thread cancel];  
        running = false;  
    }  
}  
  
- (void) startMonitor  
{  
    while (true) {  
        if ([[NSThread currentThread] isCancelled]) {  
            [NSThread exit];  
        }  
        //do your things here  
        sleep(1);  
    };  
}  
      

繼續閱讀