NSThread的建立子线程的三种方法:spa
1. //建立子线程线程
[self performSelectorInBackground:@selector(beginThread1) withObject:nil];3d
2.//建立子线程orm
[NSThread detachNewThreadSelector:@selector(beginThread2) toTarget:self withObject:nil];对象
3.第三种建立线程的方式和上面两种的区别:有返回值(当前子线程的对象),须要手动去开启线程get
//建立子线程it
NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(beginThread3) object:nil];form
//设置线程3的名称thread
thread3.name = @"thread3";object
//开启线程
[thread3 start];
线程之间的通信: 能够在一个子线程中给另外一个子线程发送指令
//仅仅只是发送指令, 具体线程5结束与否仍是得由线程5本身决定
[thread5 cancel];
接收指令的线程判断是否接收到指令,而后决定是否退出:
//若是当前线程的cancel状态为YES(被其余线程取消了)
if ([[NSThread currentThread] isCancelled]) {
NSLog(@"线程5 退出");
//退出当前线程
[NSThread exit];
}
线程加锁:
//线程锁
NSLock *lock;
-(void)beginThread6
{
for (int i=0; i<20; i++) {
[lock lock]; //加锁
//sum减1
sum--;
NSLog(@"线程6 sum=%d", sum);
//暂停1秒
[NSThread sleepForTimeInterval:1];
[lock unlock]; //解锁
}
}
线程刷新UI必须回到主线程:
//必须回到主线程刷新UI(改变progressView的进度值progress)
//waitUntilDone:是否等待回到主线程的方法执行完成
[self performSelectorOnMainThread:@selector(onMainThread:) withObject:@(i) waitUntilDone:YES];
-(void)onMainThread:(NSNumber *)i
{ //在主线程改变进度条的值
[progressView setProgress:[i floatValue] * .1 animated:YES];
}