6.18 Exiting Threads and Timers

来源:互联网 发布:ubuntu 开机任务栏没了 编辑:程序博客网 时间:2024/05/16 06:16


停止线程,停止定时器

NSThread *thread= /* Get the reference to your thread here */

[thread cancel];

NSTimer *timer= /* Get the reference to your timer here */

[timer invalidate];

请注意在退出线程时不要用exit,因为用exit的话,线程没机会清理现场,会造成内存泄露。

不过,我还真不知道如何来调用exit,因为他是类方法,一调用就报错:No visible @interface for 'NSThread' declares the selector 'exit'

看个例子


- (void) threadEntryPoint{

    @autoreleasepool {

        NSLog(@"Thread Entry Point");

        while ([[NSThreadcurrentThread] isCancelled] ==NO){

            [NSThreadsleepForTimeInterval:4];

//            if ([[NSThread currentThread] isCancelled] == NO){

               NSLog(@"Thread Loop");

//            }

        }

        NSLog(@"Thread Finished");

    }

}


- (void) stopThread{

    NSLog(@"Cancelling the Thread");

    [self.myThreadcancel];

    NSLog(@"Releasing the thread");

   self.myThread =nil;

}


-(void)test6_18

{

    self.myThread = [[NSThreadalloc] initWithTarget:self

                                           selector:@selector(threadEntryPoint)

                                             object:nil];

    [selfperformSelector:@selector(stopThread)

              withObject:nil

              afterDelay:6.0f];

    [self.myThreadstart];

}


输出:

2014-03-13 15:57:32.305 cookbook[811:360b] Thread Entry Point

2014-03-13 15:57:36.307 cookbook[811:360b] Thread Loop

2014-03-13 15:57:38.306 cookbook[811:a0b] Cancelling the Thread

2014-03-13 15:57:38.308 cookbook[811:a0b] Releasing the thread

2014-03-13 15:57:40.309 cookbook[811:360b] Thread Loop

2014-03-13 15:57:40.310 cookbook[811:360b] Thread Finished


从打印的结果可以看出,虽然线程cancel了,但是它在睡醒之后却仍然执行了一次。比较好的做法是在睡醒之后再去判断下线程是否取消了,然后在执行,如上被注释掉得那部分。


0 0