标签:
iOS开发多线程篇—创建线程
一个NSThread对象就代表一条线程
创建、启动线程
(1) NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
// 线程一启动,就会在线程thread中执行self的run方法
主线程相关用法
+ (NSThread *)mainThread; // 获得主线程
- (BOOL)isMainThread; // 是否为主线程
+ (BOOL)isMainThread; // 是否为主线程
其他用法
获得当前线程
NSThread *current = [NSThread currentThread];
线程的调度优先级:调度优先级的取值范围是0.0 ~ 1.0,默认0.5,值越大,优先级越高
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
设置线程的名字
- (void)setName:(NSString *)n;
- (NSString *)name;
其他创建线程的方式
(2)创建线程后自动启动线程 [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
(3)隐式创建并启动线程 [self performSelectorInBackground:@selector(run) withObject:nil];
上述2种创建线程方式的优缺点
优点:简单快捷
缺点:无法对线程进行更详细的设置
二、代码示例
1.使用古老的方式创建
1 //
2 // YYViewController.m
3 //
4 //
5 // Created by apple on 14-6-23.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9
10 #import "YYViewController.h"
11 #import <pthread.h>
12
13
14 @interface YYViewController ()
15 - (IBAction)btnClick;
16 @end
17
18
19 @implementation YYViewController
20
21
22 - (void)viewDidLoad
23 {
24 [super viewDidLoad];
25 }
26
27
28 //按钮的点击事件
29 - (IBAction)btnClick {
30 //1.获取当前线程
31 NSThread *current=[NSThread currentThread];
32 //主线程
33 NSLog(@"btnClick----%@",current);
34
35 //2.使用for循环执行一些耗时操作
36 pthread_t thread;
37 pthread_create(&thread, NULL, run, NULL);
38 }
39
40
41 //c语言函数
42 void *run(void *data)
43 {
44 //获取当前线程,是新创建出来的线程
45 NSThread *current=[NSThread currentThread];
46
47
48 for (int i=0; i<10000; i++) {
49 NSLog(@"btnClick---%d---%@",i,current);
50 }
51 return NULL;
52 }
53
54 //多个线程,点击按钮执行按钮调用方法的时候,主线程没有被阻塞
55
56 @end
57
58
标签:
原文地址:http://www.cnblogs.com/lhb-iOS/p/4914880.html