多线程技术总结
-
performSelectorInBackground:withObject:
-
NSThread 静态方法 + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
-
创建NSThread对象,然后调用start方法来启动线程
//第⼀一种创建线程的⽅方法
[self performSelectorInBackground:@selector(handleTask)withObject:nil];
//第⼆二种创建线程的⽅方法
withObject:nil];
//第⼀一个参数:线程要执⾏行的任务 第⼆二个参数:线程要执⾏行的任务在哪个对象⾥里 第三个参数
是:在开启线程的时候 可以传递参数
//直接创建了⼀一个线程, 创建之后, 线程直接启动
[NSThread detachNewThreadSelector:@selector(handleTask) toTarget:self
//第三种创建线程的⽅方法
selector:@selector(handleTask) object:nil];
//2、给线程起⼀一个名字myThread.name = @"Qingyun";//3、需要⼿手动启动这个线程[myThread start];
//1、创建⼀一个线程对象(NSThread)
NSThread *myThread = [[NSThread alloc ]initWithTarget:self
4. 创建NSOperation子类对象,然后使用NSOPerationQueue来启动线程
//第四种创建线程的⽅方法
initWithTarget:self selector:@selector(handleTask) object:nil];
// 3、将操作对象,添加到队列⾥里, 需要注意的是:添加队列⾥里之后,线程就开始启动[queue addOperation:operation];
//1、创建⼀一个多线程的操作队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//2、创建⼀一个操作对象,这个操作对象主要功能是定义了线程需要执⾏行的执务
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
5. 创建NSBlockOpertation对象,然后添加到NSOperationQuue来启动线程
//第五种创建线程的⽅方法
// [NSThread sleepForTimeInterval:10];
if ([thread isMainThread]) {
NSLog(@"Peer thread.thread name is %@",thread.name);
[queue addOperation:blockOperation];
//1、创建⼀一个多线程的操作队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//2、创建⼀一个NSBlockOperation对象,block本⾝身就是线程要执⾏行的具体任务
NSBlockOperation *blockOperation = [NSBlockOperation
blockOperationWithBlock:^{
NSLog(@"do thing...");
// 当前线程休眠10秒
for (long i = 0; i < 50000; i++) {
}
NSLog(@"handle:%ld",i);
// 先拿到⼀一个线程对象,返回的是表⽰示当前线程的线程对象
NSThread *thread = [NSThread currentThread];
// 通过线程对象的⽅方法来判断是否是主线程, 如果是主线程则打印⼀一条是主线程的
⽇日志, 如果不是主线程则打印⼀一条是对等线程的⽇日志
NSLog(@"Main thread.");
}else
{
}
NSLog(@"Done.");
}];
// 3、将NSBlockOperation对象添加到队列⾥里