Main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
/*
//创建Serial Dispatch Queue
dispatch_queue_t serialQueue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
//创建Concurrent Dispatch Queue
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrent queue", DISPATCH_QUEUE_CONCURRENT);
//释放,有create就应该有release
dispatch_release(serialQueue);
dispatch_release(concurrentQueue);
*/
/*
//获取系统主线程
dispatch_queue_t queue = dispatch_get_main_queue();
//获取系统创建默认的异步线程
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
*/
//dispatch_async 使用
dispatch_queue_t queue = dispatch_get_main_queue();
//死锁1
//在主线程队列里面添加一个任务,因为是同步,所以要等到添加的任务执行完才能继续往下走.
//但是新添加的任务排在队列的末尾,要执行任务必须要等这前面的任务执行完,因此又回到了第一步。程序卡死,不能输出end
// NSLog(@"begin");
// dispatch_sync(queue, ^{
// NSLog(@"sync1");
// });
// NSLog(@"end");
//死锁2
//外层 在主线程队列里面添加一个任务,因为是异步,所以不用任何添加的任务执行完就可以继续往下走,因此能够输出end
//里层 用同步添加任务到主线程队列,因此要等到添加的任务执行完才能继续往下走,程序卡死,不能输出sync1。
//经验只谈:永远也不要往主线程中同步添加事件.
// NSLog(@"begin");
// dispatch_async(queue, ^{
// dispatch_sync(queue, ^{
// NSLog(@"sync1");
// });
// });
// NSLog(@"end");
//
// [[NSRunLoop currentRunLoop] run];
Person *ps1 = [Person sharePerson];
ps1.age = 30;
Person *ps2 = [Person sharePerson];
NSLog(@"%d",ps2.age);
}
return 0;
}
Person.h
@interface Person : NSObject
@property (nonatomic, assign) int age;
+(Person *)sharePerson;
@end
Person.m
@implementation Person
static Person *instace = nil;
//+(Person *)sharePerson
//{
// @synchronized(self){
// if (!instace) {
// instace = [[Person alloc] init];
// }
// }
// return instace;
//}
+ (Person *)sharePerson
{
//使用GCD创建单利模式
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instace = [[Person alloc] init];
});
return instace;
}