-(void)buttonClick
{
// [self thread];
//[self operation];
// [self gcd];
//[self gcd2];
[self downloadImage];
}
-(void)downloadImage
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com/img/bd_logo1.png"]];
NSLog(@"下载完成");
//UI操作要在主线程里面执行
dispatch_async(dispatch_get_main_queue(), ^{
_imageView.image = [UIImage imageWithData:data];
});
});
}
-(void)gcd2
{
//组 把线程放在一个组里面,可以监听这个组里面的所有线程执行完之后,可以做一些操作
dispatch_group_t t = dispatch_group_create();
dispatch_group_async(t, dispatch_get_global_queue(0, 0), ^{
[self first];
});
dispatch_group_async(t, dispatch_get_global_queue(0, 0), ^{
[self second];
});
//被t组管理的线程全部结束后会调用这个方法
//dispatch_get_main_queue() 如果想要在子线程执行完之后,进行刷新UI操作的话,就用主线程
dispatch_group_notify(t, dispatch_get_global_queue(0, 0), ^{
NSLog(@"全部执行完成");
});
}
-(void)gcd
{
//创建一个线程队列
dispatch_queue_t t = dispatch_queue_create(NULL, NULL);
dispatch_queue_t t2 = dispatch_queue_create(NULL, NULL);
//获取一个闲置线程队列
dispatch_queue_t t3 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//把操作放在线程队列中,然后执行
dispatch_async(t, ^{
[self first];
});
//当上一个操作被执行完之后,才会执行下一个操作
//解决方法,把操作放在不同的线程队列中
dispatch_async(t2, ^{
[self second];
});
dispatch_async(t3, ^{
[self third];
});
}
-(void)operation
{
//操作队列
//queue 把操作加到队列中,操作就是代码段
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 2;
for (int i = 1; i < 10; i++) {
MyOperation *operation = [[MyOperation alloc] init];
operation.time = i;
[queue addOperation:operation];
//取消操作
//[operation cancel];
}
}
-(void)thread
{
//第一种开启线程方法
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(first) object:nil];
[thread start];
//第二种
[NSThread detachNewThreadSelector:@selector(second) toTarget:self withObject:nil];
//第三种
[self performSelectorInBackground:@selector(third) withObject:nil];
}
-(void)first
{
sleep(1);
NSLog(@"1");
}
-(void)second
{
sleep(2);
NSLog(@"2");
}
-(void)third
{
sleep(3);
NSLog(@"3");
}