Objective-c中线程NSThread的使用

来源:互联网 发布:人工智能会议 2017 编辑:程序博客网 时间:2024/06/06 07:23

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);    };}





原创粉丝点击