iOS之多线程编程:三个层次线程应用

来源:互联网 发布:重复文件清理软件 编辑:程序博客网 时间:2024/05/01 08:57
iOS支持三个层次的线程编程,从底层到高层(层次越高使用越方便,越简洁)分别是:

1:Thread;

2:Cocoa Operations;

3:Grand Central Dispatch;

简介:

Thread是抽象层次最低的,另外两种线程应用给予thread进行了封装,对于程序员而言,thread相对麻烦,需要程序员管理线程周期,但是效率最高。thread包含两种:Cocoa threads——使用NSThread 或直接从 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程;POSIX threads: 基于 C 语言的一个多线程库。

创建NSThread的方式有三种:

一:[NSThread detachNewThreadSelector:@selector(myThreadMethod:) toTarget:self withObject:nil]; 调用立即创建一个新线程执行操作
二:NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadMethod:)  object:nil]; [myThread start];     
NSThread初始化之后,新的线程并没有执行,而是调用 start 时才会创建线程执行。这种方法相对上面的方法更加灵活,在启动新的线程之前,对线程进行相应的操作,比如设置优先级,加锁。

三:[myObj performSelectorInBackground:@selector(myThreadMainMethod) withObject:nil];         利用 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程:

以上都可以在新的线程中调用performSelectorOnMainThread: withObject:waitUntilDone:更新UI,因为子线程不能直接更新UI。
线程同步与锁:

有很多时候多个线程之间会访问相同的数据,如何避免a线程和b线程之间的冲突,以及执行顺序等需要程序员考虑,这个时候需要用到NSCondition,NSLock,确保线程(原子操作)安全。

用NSCodition同步执行的顺序NSCodition 是一种特殊类型的锁,我们可以用它来同步操作执行的顺序。它与 mutex 的区别在于更加精准,等待某个 NSCondtion 的线程一直被 lock,直到其他线程给那个 condition 发送了信号。下面我们来看使用示例:

- (void)applicationDidFinishLaunching:(UIApplication *)application {  
     tickets = 100;  
     count = 0;  
     ticketCondition = [[NSCondition alloc] init];       // 锁对象 
     ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
     [ticketsThreadone setName:@"Thread-1"];  
     [ticketsThreadone start];    
     
     ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
     [ticketsThreadtwo setName:@"Thread-2"];  
     [ticketsThreadtwo start];  
     [window makeKeyAndVisible];   
}  
   
- (void)run{  
     while (TRUE) {   
         [ticketsCondition lock];  // 上锁  
         if(tickets > 0){  
             [NSThread sleepForTimeInterval:0.5];  
             count = 100 - tickets;  
             NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);  
             tickets--;  
         } else {  
             break;  
         }  
         [ticketsCondition unlock];  
     }  
}  

线程间通信,交互
在应用程序主线程中做事情:
performSelectorOnMainThread:withObject:waitUntilDone:
performSelectorOnMainThread:withObject:waitUntilDone:modes:
在指定线程中做事情:
performSelector:onThread:withObject:waitUntilDone:
performSelector:onThread:withObject:waitUntilDone:modes:
在当前线程中做事情:
performSelector:withObject:afterDelay:
performSelector:withObject:afterDelay:inModes:
取消发送给当前线程的某个消息
cancelPreviousPerformRequestsWithTarget:
cancelPreviousPerformRequestsWithTarget:selector:object:

Cocoa Operetions

0 0
原创粉丝点击