NSThread exit 方法

+ (void)exit

Terminates the current thread.

Discussion

This method uses the currentThread class method to access the current thread. Before exiting the thread, this method posts the NSThreadWillExitNotification with the thread being exited to the default notification center. Because notifications are delivered synchronously, all observers of NSThreadWillExitNotification are guaranteed to receive the notification before the thread exits.

Invoking this method should be avoided as it does not give your thread a chance to clean up any resources it allocated during its execution.

之前一直以为运行中的线程是不可以结束掉的,但是看到手册里的这个方法,发现是可以结束的。
这个方法是用来Exit当前线程,如果在Main Thread里调用此方法,会Exit Main Thread。
在Exit Thread之前系统会发出 NSThreadWillExitNotification的通知。
下面是例子:

[[NSNotificationCenter defaultCenter] addObserver:self 

                                             selector:@selector(threadWillExitNotification:) 

                                                 name:@"NSThreadWillExitNotification" 

                                               object:nil];

    

[NSThread detachNewThreadSelector:@selector(method3) toTarget:self withObject:nil];

[NSThread detachNewThreadSelector:@selector(method4) toTarget:self withObject:nil];


- (void)method3

{

    NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];

    [[NSThread currentThread] setName:@"MyThread"];

    int n = 0;

    while (1) {

        NSLog(@"n -> %d", n);

        if (n > 10) {

            [[NSThread currentThread] cancel];

        }

        

        if ([[NSThread currentThread] isCancelled]) {

            [NSThread exit];

        }

        n++;

    }

    

    

    [apool drain];

}



- (void)method4

{

    NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];

    int m = 0;

    while (1) {

        NSLog(@"m -> %d", m);

        m++;

    }

    

    

    [apool drain];

}


- (void)threadWillExitNotification:(NSNotification *)notification

{

    NSLog(@"notification -> %@", notification);

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值