GCD同步异步测试DEMO

转自 <a target=_blank class="cut cut70" href="http://blog.csdn.net/weisubao/article/details/41958799?utm_source=tuicool&utm_medium=referral" style="color: rgb(51, 51, 51); text-decoration: none; -webkit-transition: 0.25s; transition: 0.25s; outline: none 0px; overflow: hidden; white-space: nowrap; word-break: keep-all; text-overflow: ellipsis; max-width: 69%; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; font-size: 14px; display: inline-block;">http://blog.csdn.net/weisubao/article/details/41958799</a>
/**
 *  因为是异步,所以开通了子线程,但是因为是串行队列,所以只需要开通1个子线程(2),它们在子线程中顺序执行。最常用。
 */
-(void)gcdDemo1{
    dispatch_queue_t q1=dispatch_queue_create("com.hellocation.gcdDemo", DISPATCH_QUEUE_SERIAL);
    for (int i=0; i<10; i++) {
        dispatch_async(q1, ^{
            NSLog(@"%@",[NSThread currentThread]);
        });
    }
}
/**
 *  因为是异步,所以开通了子线程,且因为是并行队列,所以开通了好多个子线程,具体几个,无人知晓,看运气。线程数量无法控制,且浪费。
 */
-(void)gcdDemo2{
    dispatch_queue_t q2=dispatch_queue_create("com.hellocation.gcdDemo", DISPATCH_QUEUE_CONCURRENT);
    for (int i=0; i<10; i++) {
        dispatch_async(q2, ^{
            NSLog(@"%@",[NSThread currentThread]);
        });
    }
}
/**
 *  因为是同步,所以无论是并行队列还是串行队列,都是在主线程中执行
 */
-(void)gcdDemo3{
    dispatch_queue_t q1=dispatch_queue_create("com.hellocation.gcdDemo", DISPATCH_QUEUE_CONCURRENT);
    for (int i=0; i<10; i++) {
        dispatch_sync(q1, ^{
            NSLog(@"%@",[NSThread currentThread]);
        });
    }
}
/**
 *  全局队列和并行队列类似(全局队列不需要创建直接get即可,而导致其没有名字,不利于后续调试)
 */
-(void)gcdDemo5{
    dispatch_queue_t q=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    for (int i=0; i<10; i++) {
        dispatch_sync(q, ^{
            NSLog(@"1-%@",[NSThread currentThread]);
        });
    }
    for (int i=0; i<10; i++) {
        dispatch_async(q, ^{
            NSLog(@"2-%@",[NSThread currentThread]);
        });
    }
}
/**
 *  因为是主线程,所以异步任务也会在主线程上运行(1)。而如果是同步任务,则阻塞了,因为主线程一直会在运行,所以后米的任务永远不会被执行。
 *  主要用处,是更新UI,更新UI一律在主线程上实现
 */
-(void)gcdDemo6{
    dispatch_queue_t q=dispatch_get_main_queue();
//    for (int i=0; i<10; i++) {
//        dispatch_sync(q, ^{
//            NSLog(@"%@",[NSThread currentThread]);
//        });
//    }
	for (int i=0; i<10; i++) {
		dispatch_async(q, ^{
			NSLog(@"%@",[NSThread currentThread]);
		});
	}
}

猜你喜欢

转载自blog.csdn.net/lipeiran1987/article/details/51329808