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];
}