+ (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.
之前一直以为运行中的线程是不可以结束掉的,但是看到手册里的这个方法,发现是可以结束的。[[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);
}