线程NSThread的使用

动态创建

NSThread * newThread = [[NSThread alloc]initWithTarget:self 

selector:@selector(threadRun) object:nil];

动态方法返回一个新的thread对象,需要调用start方法来启动线程


静态创建

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

由于静态方法没有返回值,如果需要获取新创建的thread,需要在selector中调用获取当前线程的方法


线程开启

[newThread start];


线程暂停

[NSThread sleepForTimeInterval:1.0]; (以暂停一秒为例)

[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];

NSThread的暂停会有阻塞当前线程的效果


线程取消

[newThread cancel];

取消线程并不会马上停止并退出线程,仅仅只作(线程是否需要退出)状态记录


线程停止

[NSThread exit];

停止方法会立即终止除主线程以外所有线程(无论是否在执行任务)并退出,需要在掌控所有线程状态的情况下调用此方法,

否则可能会导致内存问题。



获取当前线程

[NSThread currentThread];


获取主线程

[NSThread mainThread];

猜你喜欢

转载自blog.csdn.net/mr_tangit/article/details/80612900