您的位置:首页 > 其它

GCD多线程2

2015-07-16 15:27 274 查看
一、主队列:是和主线程相关联的队列,主队列是GCD自带的一种特殊的串行队列,放在主队列中得任务,都会放到主线程中执行。

如果把任务放到主队列中进行处理,那么不论处理函数是异步的还是同步的都不会开启新的线程。

(1)使用异步函数执行主队列中的任务

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

NSLog(@"%@",[NSThread mainThread]);

dispatch_queue_t mainQueue = dispatch_get_main_queue();

dispatch_async(mainQueue, ^{
NSLog(@"使用异步函数执行主队列中的任务1--%@",[NSThread currentThread]);
});

dispatch_async(mainQueue, ^{
NSLog(@"使用异步函数执行主队列中的任务2--%@",[NSThread currentThread]);
});
dispatch_async(mainQueue, ^{
NSLog(@"使用异步函数执行主队列中的任务3--%@",[NSThread currentThread]);
});
}


打印结果:



(2)使用同步函数,在主线程中执行主队列中的任务,会发生死循环

二、

1、任务1单独开启一个新的线程,任务2在主线程执行。

- (void)viewDidLoad
{
[super viewDidLoad];
//开启一个后台线程,调用执行test方法
[self performSelectorInBackground:@selector(test) withObject:nil];
}

-(void)test
{
NSLog(@"当前线程---%@",[NSThread currentThread]);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

//异步函数
dispatch_async(queue, ^{
NSLog(@"任务1所在的线程----%@",[NSThread currentThread]);
});

//同步函数
dispatch_sync(queue, ^{
NSLog(@"任务2所在的线程----%@",[NSThread currentThread]);
});
}


打印结果:


2.在子线程加载图片完毕后,主线程拿到加载的image刷新UI界面

- (void)viewDidLoad
{
[super viewDidLoad];

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//1.获取一个全局串行队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2.把任务添加到队列中执行
dispatch_async(queue, ^{

//打印当前线程
NSLog(@"%@",[NSThread currentThread]);
//3.从网络上下载图片
NSURL *urlstr=[NSURL URLWithString:@"http://upload.ct.youth.cn/2015/0608/1433725303485.jpg"];
NSData *data=[NSData dataWithContentsOfURL:urlstr];
UIImage *image=[UIImage imageWithData:data];
//提示
NSLog(@"图片加载完毕");

dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
//打印当前线程
NSLog(@"%@",[NSThread currentThread]);
});
});
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: