多线程简介
- 首先来了解下另一个概念进程:
一个运行中的应用程序就是一个进程,当程序开始执行时,操作系统给进程分配地址空间,然后把他的代码加载到代码段,然后给进程创建一个线程,称之为主线程(!!!!!所有的界面操作都必须在主线程中执行),由于线程是CPU分配的基本单位,所以开始分配CPU,由CPU执行你的应用程序 - 线程:把不同的任务放到不通的线程当中去,解决界面卡死问题,程序中的一个执行序列,他必须存在于进程的地址空间中,一个进程可以包含多个进程,但是一个线程只能属于一个进程
- NSThread线程创建的方式有三种:
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 监听线程结束
[[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发cancel消息.仅仅只是发消息,处不处理,由_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");
//执行线程退出
[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];
}
网友评论