NSThread

 1 多线程编程1--NSTread
 2 iOS中多线程编程方法有4种,3种常用的
 3 1.pThread (底层 c线程库,很少用到)
 4 2.NSThread(oc线程库,这篇博客将介绍一些关于它的知识)
 5 这种方法需要管理线程的生命周期、同步、加锁问题,会导致一定的性能开销
 6 3.NSOperation和NSOperationQueue(线程池/线程队列)
 7 是基于oc实现的。NSOperation 以面向对象的方式封装了需要执行的操作,然后可以将这个操作放到一个NSOpreationQueue中去异步执行。不必关心线程管理、同步等问题
 8 4.GCD(Grand Centeral Dispatch)
 9 ios4才开始支持,是纯C语言的API.自ipad2开始,苹果设备开始有了双核CPU,为了充分利用这2个核,GCD提供了一些新特性来支持多核并行编程
10 
11 下面进入NSTread的介绍
12 
13 一 、获取当前线程
14 NSThread *current = [NSThread currentThread];
15 
16 二、获取主线程
17 NSThread *mainThread = [NSThread mainThread];
18 NSLog(“主线程:%@“mianThread);
19 
20 打印结果是:
21 2015-08-28 21:36:38.599 thread[7499:c07] 主线程:<NSThread: 0x71434e0>{name = (null), num = 1}
22 num相当于线程的id,主线程的num是1
23 三、NSThread的创建
24 1.动态方法
25 -(id)initWithThread:(id)target selector:(SEL)selector object:(id)argument;
26 //创建
27 NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(doWCing) object:nil];
28 //可以命名
29 thread.name = @“子线程”;
30 //使用alloc创建的线程,一定要显示调用start方法,才能运行
31 [thread start];
32 //取消线程
33 [thread cancel];
34 2.静态方法
35 +(void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
36 //创建
37 [NSThread detachNewThreadSelector:@selector(doWCing) toTarget:self withObject:nil];
38 //取消
39 [NSThread exit];
40 
41 上面的两种方式中的withObject:代表的是要传入的参数
42 
43 四、暂停当前线程
44 [NSThread sleepForTimeInterval:2];//让线程暂停2秒
45 
46 五。线程的其他执行操作
47 1.在指定线程上执行操作
48 [self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
49 上面代码的意思是在thread这条线程上调用self的run方法,最后的YES代表:上面的代码会阻塞,等run方法在thread线程执行完毕后,上面的代码才会通过
50 2.在主线程上执行操作
51 [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
52 在主线程调用self的run方法
53 3.在当前线程执行操作
54 [self performSelector:@selector(run) withObject:nil];
55 在当前线程调用self的run方法。
56 
57 六、优缺点
58 1.优点:NSThread 比其他多线程方案较轻量级,更直观地控制线程对象
59 2.缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的性能开销。
View Code
原文地址:https://www.cnblogs.com/sdutmyj/p/4773938.html