原文
- (void)synchronizadTest2 {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"线程A,准备好");
@synchronized(self){
NSLog(@"线程A lock, 请等待");
[NSThread sleepForTimeInterval:3];
NSLog(@"线程A 执行完毕");
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"线程B,准备好");
//相当于 对整个 对象 都加锁
@synchronized(self){
NSLog(@"线程B lock, 请等待");
[NSThread sleepForTimeInterval:1];
NSLog(@"线程B 执行完毕");
}
});
}
>打印结果
2017-03-17 11:30:47.312 同步锁[3600:51507] 线程B,准备好
2017-03-17 11:30:47.312 同步锁[3600:51506] 线程A,准备好
2017-03-17 11:30:47.313 同步锁[3600:51507] 线程B lock, 请等待
2017-03-17 11:30:48.382 同步锁[3600:51507] 线程B 执行完毕
2017-03-17 11:30:48.383 同步锁[3600:51506] 线程A lock, 请等待
2017-03-17 11:30:51.452 同步锁[3600:51506] 线程A 执行完毕
- (void)synchronizadTest {
static NSObject *lock = nil;
if (!lock) {
lock = [[NSString alloc] init];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"线程A,准备好");
@synchronized(lock){
NSLog(@"线程A lock, 请等待");
[NSThread sleepForTimeInterval:3];
NSLog(@"线程A 执行完毕");
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"线程B,准备好");
@synchronized(lock){
NSLog(@"线程B lock, 请等待");
[NSThread sleepForTimeInterval:1];
NSLog(@"线程B 执行完毕");
}
});
}
打印结果
2017-03-17 11:32:17.982 同步锁[3626:52584] 线程B,准备好
2017-03-17 11:32:17.982 同步锁[3626:52587] 线程A,准备好
2017-03-17 11:32:17.983 同步锁[3626:52584] 线程B lock, 请等待
2017-03-17 11:32:19.053 同步锁[3626:52584] 线程B 执行完毕
2017-03-17 11:32:19.053 同步锁[3626:52587] 线程A lock, 请等待
2017-03-17 11:32:22.124 同步锁[3626:52587] 线程A 执行完毕
- (void)NSLookTest {
static NSLock *lock = nil;
if (!lock) {
lock = [[NSLock alloc] init];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"线程A,准备好");
[lock lock];
NSLog(@"线程A lock, 请等待");
[NSThread sleepForTimeInterval:3];
NSLog(@"线程A 执行完毕");
// 这里如果注释了 其他地方 就不能访问了
[lock unlock];
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"线程B,准备好");
[lock lock];
NSLog(@"线程B lock, 请等待");
[NSThread sleepForTimeInterval:1];
NSLog(@"线程B 执行完毕");
[lock unlock];
});
}
网友评论