iOS中的多线程方案如下:
1. NSThread
NSThread线程创建
/**
* 创建线程的方式1
*/
- (void)createThread1
{
// 创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"];
thread.name = @"下载线程";
// 启动线程(调用self的download方法)
[thread start];
}
/**
* 创建线程的方式2
*/
- (void)createThread2
{
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
}
/**
* 创建线程的方式3
*/
- (void)createThread3
{
// 这2个不会创建线程,在当前线程中执行
// [self performSelector:@selector(download:) withObject:@"http://c.gif"];
// [self download:@"http://c.gif"];
[self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
}
NSThread的类方法
[NSThread currentThread]
[NSThread mainThread]
NSThread线程状态
// 睡眠5秒钟
[NSThread sleepForTimeInterval:5];
// 3秒后的时间
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];
[NSThread sleepUntilDate:date];
//线程退出
for (int i = 0; i<100; i++) {
NSLog(@"------%d", i);
if (i == 49) {
[NSThread exit];
}
}
2. GCD
后台异步并发队列(常用)
// 获得全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 将 任务 添加 全局队列 中去 异步 执行
dispatch_async(queue, ^{
NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
});
后台异步串行队列
// 1.创建一个串行队列
dispatch_queue_t queue = dispatch_queue_create("cn.heima.queue", NULL);
// 2.将任务添加到串行队列中 异步 执行
dispatch_async(queue, ^{
NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
});
前台异步串行队列(常用)
// 1.主队列(添加到主队列中的任务,都会自动放到主线程中去执行)
dispatch_queue_t queue = dispatch_get_main_queue();
// 2.添加 任务 到主队列中 异步 执行
dispatch_async(queue, ^{
NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
});
同步执行
使用dispatch_sync可以同步执行,即执行完block的内容,再往后执行
dispatch_sync(queue, ^{
NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
});