iOS中的多线程编程技术有三种,包括NSThread、NSOperation、GCD;今天先说一下前两种多线程技术的应用。
一、NSThread来创建一个多线程,有两种方法来创建多线程;
1.工厂方法来创建一个多线程。
- [NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self
- withObject:@"hi"];
- NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(doSomething:)
- object:@"hi"];
- [thread start];
3.利用perform来创建一个多线程。
1)创建一个多线程
- [self performSelectorInBackground:@selector(doSomething) withObject:@"hi"];
2)利用perform执行切换到主线程并执行一些列动作。
- self performSelectorOnMainThread:@selector(doSomething) withObject:@"hi"
- waitUntilDone:YES];
3)在指定线程中执行,需要注意的一点是:这个线程必须具备run loop
4.NSOperation创建线程的方法。
1) 利用NSOperation来创建多线程的时候,首先要创建一个线程队列,然后定义子任务,这些子任务则必须是NSOperation的子类。然后将这些子任务添加到线程队列中,则会自动开启多线程。
a.创建一个队列
- NSOperationQueue queue =[[NSOperationQueue alloc]init];
- NSInvocationOperation operation =[[NSInvocationOperation alloc]initWithTarget:self
- selector:@selector(doSomething:) object:@"hi"];
- [queue addOperation:operation];
2)利用block快来添加数据
- NSOperationQueue queue =[[NSOperationQueue alloc]init];
- NSBlockOperation operation =[NSBlockOperation blockOperationWithBlock:^{ [self doSomething]}];
- [queque addOperation:oper];
5.常见的一些NSThread的方法:
1. +(NSThread *)currentThread; //获得当前线程
2. +(void)sleepForTimeInterval:(NSTimeInterval)ti; //线程休眠
3. +(NSThread *)mainThread; //主线程,亦即UI线程了
4. -(BOOL)isMainThread; + (BOOL)isMainThread; //当前线程是否主线程
5. -(BOOL)isExecuting; //线程是否正在运行
6. -(BOOL)isFinished; //线程是否已结束