天天看点

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.使用古老的方式创建

iOS开发多线程篇—创建线程
iOS开发多线程篇—创建线程

实现效果:

iOS开发多线程篇—创建线程

打印结果:

iOS开发多线程篇—创建线程

2.使用nsthread创建线程

iOS开发多线程篇—创建线程
iOS开发多线程篇—创建线程

调用线程1,打印结果为:

iOS开发多线程篇—创建线程

调用线程2

iOS开发多线程篇—创建线程

调用线程3

iOS开发多线程篇—创建线程

继续阅读