因为不常用,所以NSThread需要掌握的没有多少,会这些就够了:
1.创建方式:
-------
(1)创建后启动
NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"先创建,后启动"];
[thread start];
(2)创建后立即启动
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"创建自动启动"];
(3)隐式启动
[self performSelectorInBackground:@selector(download:) withObject:@"隐式创建"];
2.常用方法:
-------
(1)获得主线程:
[NSThread mainThread];
(2)获得当前线程:
[NSThread currentThread];
(3)设置线程名字(调试用):
[[NSThread currentThread] setName:@"thread1"];
(4)NSThread互斥锁 保证原子 尽量不用:
@synchronized(self) {//加锁部分代码
}
(5)NSThread线程间通信(下载完成后回到主线程中更新UI):
[self performSelectorOnMainThread:@selector(setImageAfterDownload:) withObject:image waitUntilDone:YES];
或者要设置imageView的图片时候可以这样:[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];