这一久正在学习多线程编程,现在将自己学习总结跟大家分享一下
iOS提供了如下3种多线程编程的技术
>使用NSThread实现多线程
>使用NSOperation与NSOperationQueue实现多线程
>使用GCD(Grand Central Dispatch)实现多线程
这三种编程方式从上到下 抽象度层次是从低到高的 抽象度越高的用法越简单
- (void)viewDidLoad {
[super viewDidLoad];
#pragma mark-使用NSThread实现多线程
// 创建和启动线程
// 创建NSthread有两种方式
// >initWithTarget:<#(id)#> selector:<#(SEL)#> object:<#(id)#> 只创建需要手动启动
// >detachNewThreadSelector:<#(SEL)#> toTarget:<#(id)#> withObject:<#(id)#> 创建并启动
for (int i = 0; i < 30; i ++) {
NSLog(@"===%@===%i", [NSThread currentThread], i);
if (i == 20) {
// 创建线程对象
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
// 启动新线程
[thread start];
// 创建并启动新线程
// [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}
}
}
- (void)run{
for (int i = 0; i < 30; i++) {
// [NSThread currentThread] 当前线程
// 可以通过setName:方法为线程设置名字 也可以通过name方法返回指定线程的名字
NSLog(@"---%@---%i", [NSThread currentThread], i);
}
}