OS中多线程的实现方案:
技术 | 语言 | 线程生命周期 | 使用频率 |
pthread | C | 程序员自行管理 | 几乎不用 |
NSthread | OC | 程序员自行管理 | 偶尔使用 |
GCD | C | 自动管理 | 经常使用 |
NSOperation | OC | 自动管理 | 经常使用 |
线程的状态
NSThread的创建方式:
1
2
3
4
5
6
7
8
9
10
11
12
|
//创建线程方式一 NSThread *threadOne = [[ NSThread alloc] initWithTarget: self selector: @selector (testAction) object: nil ]; //给线程命名 threadOne.name = @ "threadOne" ; //启动线程,在新开的线程执行testAction方法 [threadOne start]; //创建线程方式二,并且会自动启动 [ NSThread detachNewThreadSelector: @selector (testAction) toTarget: self withObject: nil ]; //创建线程方式三,隐式创建方式,自动启动 [ self performSelectorInBackground: @selector (testAction) withObject: nil ]; |
调用的方法
1
2
3
4
5
6
7
|
- ( void )testAction { for ( int i = 0; i < 3; i++) { NSLog (@ "i = %d,当前线程 = %@" ,i,[ NSThread currentThread]); } } |
结果:可以看到有3条线程并发执行
线程的属性:
1
2
3
4
5
6
|
//创建一个线程 NSThread * thread = [[ NSThread alloc] initWithTarget: self selector: @selector (testAction) object: nil ]; //线程名字 thread .name = @ "wl" ; //线程优先级,一般情况不设置,默认0.5,数值范围0-1,数值越大优先级越高 thread .threadPriority = 0.5; |
常用方法,这些都是类方法,相对于这段代码所在的线程进行操作
1
2
3
4
5
6
7
8
9
10
11
12
|
//获得主线程 [ NSThread mainThread]; //判断是否为主线程,返回一个BOOL值 BOOL isMainThread = [ NSThread isMainThread]; //判断是否为多线程,返回一个BOOL值 BOOL isMultiThreaded = [ NSThread isMultiThreaded]; //把线程从可调度线程池中移除2s(阻塞线程) [ NSThread sleepForTimeInterval:2]; //把线程从可调度线程池中移除直到一个时间点(阻塞线程) [ NSThread sleepUntilDate:[ NSDate dateWithTimeIntervalSinceNow:2]]; //停止线程,线程死亡,这个线程就已经不存在了 [ NSThread exit]; |