/*
1 主队列(串行) Main Queue
2 全局队列 Global Queue
3 自己创建的队列 create
如果队列里有多个任务,GCD会根据系统的负载合理的分配线程数,不能自己设置并发的数量
*/
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// [self getMainQueue];
// [self getGlobalQueue];
[selfcreateQueue];
}
#pragma mark -- 获取主队列
-(void)getMainQueue
{
// 1队列名称 2 block块里边放的是任务列表
// dispatch是GCD里面常用的变量及函数名前缀
dispatch_async(dispatch_get_main_queue(), ^{
//休眠
sleep(1.0);
//打印当前线程
NSLog(@"currentThread == %@",[NSThreadcurrentThread]);
//是否是主线程
NSLog(@"isMain == %d",[NSThreadisMainThread]);
//判断当前是否是多线程
NSLog(@"ismutiple == %d",[NSThreadisMultiThreaded]);
});
}
#pragma mark -- 全局队列
-(void)getGlobalQueue
{
// 1创建队列
//1 运行优先标志(高,默认,低,后台) 2参数标志,给个0就行
dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0);
// dispatch_get_global_queue全局队列,
/*
在队列里边可以运行多个任务,每个任务的启动时间,是按照加入队列里的任务来的---先进先出
全局队列能够实现并行,获取不同的全局队列开启线程不同,我们不能创建全局队列,只能获取和调度
*/
//在全局队列里添加任务
//按照顺序执行
dispatch_async(queue, ^{
[selfprintFirst];
[selfprintSecond];
});
}
#pragma mark -- 创建队列
-(void)createQueue
{
//前边是接受队列 后边是创建队列的函数
// 1参数 队列的标识
// 2参数 分配是串行队列还是串行队列,可以置为NULL
//队列的类型 dispatch_queue_t
//并行队列 DISPATCH_QUEUE_CONCURRENT
//串行队列 DISPATCH_QUEUE_SERIAL
dispatch_queue_t myQueue =dispatch_queue_create("myQueue",DISPATCH_QUEUE_CONCURRENT);
/* //队列的同步演示
//只要是同步的,就不会开辟线程
dispatch_sync(myQueue, ^{
//创建线程数
NSLog(@"currentThread == %@",[NSThread currentThread]);
//判断当前是否是多线程
NSLog(@" isMultiThread == %d",[NSThread isMultiThreaded]);
[self printFirst];
[self printThree];
});
dispatch_sync(myQueue, ^{
[self printSecond];
});
*/
// #if 0
//异步队列演示 自动开辟新线程
dispatch_async(myQueue, ^{
NSLog(@"currentThread == %@",[NSThreadcurrentThread]);
//判断当前是否是多线程
NSLog(@"ismutiple == %d",[NSThreadisMultiThreaded]);
//在队列里的任务是串行的
[selfprintFirst];
[selfprintThree];
});
dispatch_async(myQueue, ^{
[selfprintSecond];
[selfprintFour];
});
// #endif
}
#pragma mark -- 任务1
-(void)printFirst
{
for (int i =0; i <2; i++) {
[NSThreadsleepForTimeInterval:1.0];
NSLog(@"action task 1 -- %d",i);
}
}
#pragma mark -- 任务2
-(void)printSecond
{
for (int i =3; i <6; i++) {
[NSThreadsleepForTimeInterval:1.0];
NSLog(@"action task 2 -- %d",i);
}
}
#pragma mark -- 任务3
-(void)printThree
{
for (int i =7; i <11; i++) {
[NSThreadsleepForTimeInterval:1.0];
NSLog(@"action task 3 -- %d",i);
}
}
#pragma mark -- 任务4
-(void)printFour
{
for (int i =12; i <15; i++) {
[NSThreadsleepForTimeInterval:1.0];
NSLog(@"action task 4 -- %d",i);
}
}
//GCD应用实例之一
/*//获取全局队列
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
NSError * error;
NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (data !=nil) {
//回到主线程打印数据
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"data is: %@", data);
});
} else {
NSLog(@"error:%@", error);
}
});
*/
欢迎交流指正Demo下载:http://download.csdn.net/detail/bddzzw/9598720