//
// PJViewController.m
// 队列
//
// Created by pj on 14-8-2.
// Copyright (c) 2014年 pj. All rights reserved.
//
#import "PJViewController.h"
@interface PJViewController ()
@end
@implementation PJViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self demo4];
}
// 主队列
- (void)demo4
{
// 1.获取主队列
dispatch_queue_t q = dispatch_get_main_queue();
// 2.添加异步任务,这里会开1条线程,因为他是在主队列里面的
for (int i = 0; i < 100; i++) {
dispatch_async(q, ^{
NSLog(@"%@",[NSThread currentThread]);
});
}
// 这个是死锁,因为他会等到主线程执行完毕后,才会执行这个方法,所以会是死锁
dispatch_sync(q, ^{
NSLog(@"%@",[NSThread currentThread]);
});
}
// 全局并行队列
- (void)demo3
{
// 1.获取全局队列
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 2.添加异步任务,这里会开N条线程,因为他是在并行队列里面的
for (int i = 0; i < 100; i++) {
dispatch_async(q, ^{
NSLog(@"%@",[NSThread currentThread]);
});
}
}
- (void)demo2
{
// 1.创建并行队列,能开N条线程
dispatch_queue_t q = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT);
// 2.添加异步任务,这里会开N条线程,因为他是在并行队列里面的
// for (int i = 0; i < 100; i++) {
// dispatch_async(q, ^{
// NSLog(@"%@",[NSThread currentThread]);
// });
// }
// 3.添加同步任务,同步任务是在主线程上执行,不会开启新的线程
for (int i = 0; i < 100; i++) {
dispatch_sync(q, ^{
NSLog(@"%@",[NSThread currentThread]);
});
}
}
- (void)demo1
{
// 1.创建串行队列,只能开一条线程
dispatch_queue_t q = dispatch_queue_create("myqueue", DISPATCH_QUEUE_SERIAL);
// 2.添加任务
// 他只会在一个异步线程执行
for (int i = 0; i < 100; i++) {
dispatch_async(q, ^{
NSLog(@"%@",[NSThread currentThread]);
});
}
}
@end