1、什么是进程?什么是线程?什么是主线程?
一个任务就是一个进程,(手机中启动一个软件,就有一个进程)
一个进程至少有一个线程(当然可以有多个线程)
一个程序启动后,就会有一个主线程(看到的界面,显示界面的线程就是主线程)
2、什么是多线程?
多个线程并发执行,完成一个或多个目标。
3、开启多线程的几个方法?
1)NSThread实现
//第一步:实例化NSThread
NSThread *thread= [[NSThread alloc] initWithTarget:self selector:@selector(mulitiThread:)object:@"xxxxxxx"];
//第二步:开启线程,start
[ thread start];
// 调用方法:
//子线程的方法
-(void)mulitiThread:(NSString*) _str{
for (int i=0; i<100; i++) {
NSLog(@"%@:%d",_str,i);
}
//当子线程执行完成以后,跳转到主线程执行
[selfperformSelectorOnMainThread:@selector(mainThread) withObject:nilwaitUntilDone:YES];
}
2)detachNewThreadSelector
[NSThreaddetachNewThreadSelector:@selector(mulitiThread:) toTarget:selfwithObject:@"yyyyy"];
3)设置后台运行(NSObject)
[selfperformSelectorInBackground:@selector(mulitiThread:)withObject:@"xxxxxxxx"];
4)线程队列
//定义一个线程的队列
NSOperationQueue *queue =[[NSOperationQueue alloc] init];
//设定多线程的并发数量
queue.maxConcurrentOperationCount = 2;
//定义线程1
NSInvocationOperation *t1 =[[NSInvocationOperation alloc] initWithTarget:selfselector:@selector(mulitiThread:) object:@"thread1"];
//把线程加入到线程队列中
[queue addOperation:t1];
//定义线程2
//定义线程1
NSInvocationOperation *t2 =[[NSInvocationOperation alloc] initWithTarget:selfselector:@selector(mulitiThread2:) object:@"thread2"];
//把线程加入到线程队列中
[queue addOperation:t2];
//把线程1和2添加到线程队列中
5)GCD方式
dispatch_queue_tque1 = dispatch_queue_create("que1", NULL);
//开启一个异步操作
dispatch_async(que1, ^{
for (int i=0; i<100; i++) {
NSLog(@"子线程:%d",i);
}
// BOOL isMulitiThread = [NSThreadisMultiThreaded];
// if (!isMulitiThread) {
// NSLog(@"这是多线程~");
// }
//开始一个同步的任务,返回主线程
//dispatch_get_main_queue() 返回主线程
dispatch_sync(dispatch_get_main_queue(), ^{
//返回到界面
if ([NSThread isMainThread]) {
NSLog(@"这是主线程");
}
});
});