多線程簡介
- 首先來了解下另一個概念進程:
一個運行中的應(yīng)用程序就是一個進程,當(dāng)程序開始執(zhí)行時,操作系統(tǒng)給進程分配地址空間,然后把他的代碼加載到代碼段,然后給進程創(chuàng)建一個線程,稱之為主線程(!!!!!所有的界面操作都必須在主線程中執(zhí)行),由于線程是CPU分配的基本單位,所以開始分配CPU,由CPU執(zhí)行你的應(yīng)用程序 - 線程:把不同的任務(wù)放到不通的線程當(dāng)中去,解決界面卡死問題,程序中的一個執(zhí)行序列,他必須存在于進程的地址空間中,一個進程可以包含多個進程,但是一個線程只能屬于一個進程
- NSThread線程創(chuàng)建的方式有三種:
1、[self performSelectorInBackground:@selector(thread1) withObject:nil];
2、[NSThread detachNewThreadSelector:@selector(thread2:) toTarget:self withObject:@(100)];
3、
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread3) object:nil];
[thread setName:@"thread3"];
[thread start];
2.2 監(jiān)聽線程結(jié)束
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(myThreadFinish:) name:NSThreadWillExitNotification object:nil];
- (void)myThreadFinish:(NSNotification *)notification
{
NSThread *thread = [notification object];
if ([thread.name isEqualToString:@"thread3"])
{
NSLog(@"thread3 finish!");
}
NSLog(@"thread ===%@",thread);
}
2.3 線程間通訊
- (void)thread4
{
for (int i = 0; i<10; i++)
{
NSLog(@"thread4 i===%d",i);
[NSThread sleepForTimeInterval:1.0];
if (i == 8)
{
//給_thread5發(fā)cancel消息.僅僅只是發(fā)消息,處不處理,由_thread5自己決定
[_thread5 cancel];
}
}
}
- (void)thread5
{
int i = 0;
while (1)
{
NSLog(@"thread5===%d",i);
[NSThread sleepForTimeInterval:1.0];
i++;
//如果thread5 接收到了cancel消息,就退出
if ([[NSThread currentThread]isCancelled])
{
NSLog(@"thread5 exit");
//執(zhí)行線程退出
[NSThread exit];
}
}
}
2.4 線程鎖
```
_sumLock = [[NSLock alloc]init];
_sum = 0;
[_sumLock lock];
_sum ++;
[NSThread sleepForTimeInterval:1.0];
[_sumLock unlock];
2.5 子線程刷新UI
_progress = [[UIProgressView alloc]initWithFrame:CGRectMake(100, 100, 200, 30)];
[self.view addSubview:_progress];
[self performSelectorInBackground:@selector(myThread) withObject:nil];
- (void)myThread
{
for (int i=1; i<11; i++)
{
[self performSelectorOnMainThread:@selector(myMain:) withObject:@(i) waitUntilDone:YES];
[NSThread sleepForTimeInterval:1];
}
}
- (void)myMain:(NSNumber *)number
{
NSLog(@"number==%@",number);
[_progress setProgress:number.floatValue*0.1 animated:YES];
}