iOS http://www.cnblogs.com/luoguoqiang1985/p/3495800.html
Android http://www.jianshu.com/p/9474d64575b0
- 1.@synchronized对象锁
static NSObject *lockObj = nil;
if (lockObj == nil) {
lockObj = [[NSObject alloc] init];
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"A thread try lock!");
@synchronized(lockObj) {
NSLog(@"A thread lock, please wait!");
[NSThread sleepForTimeInterval:10];
NSLog(@"A thread unlock!");
}
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"B thread try lock!");
@synchronized(lockObj) {
NSLog(@"B thread lock, please wait!");
[NSThread sleepForTimeInterval:5];
NSLog(@"B thread unlock!");
}
});
- 2.NSLock
if (lockMain == nil) {
lockMain = [[NSLock alloc] init];
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[lockMain lock];
NSLog(@"A thread begin +!");
[NSThread sleepForTimeInterval:10];
NSLog(@"A thread + done and unlock!");
[lockMain unlock];
[lockMain lock];
NSLog(@"A thread begin -!");
[NSThread sleepForTimeInterval:10];
NSLog(@"A thread - done and unlock!");
[lockMain unlock];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[lockMain lock];
NSLog(@"B thread begin *!");
[NSThread sleepForTimeInterval:10];
NSLog(@"B thread * done and unlock!");
[lockMain unlock];
[lockMain lock];
NSLog(@"B thread begin /!");
[NSThread sleepForTimeInterval:10];
NSLog(@"B thread / done and unlock!");
[lockMain unlock];
});
- 3.NSConditionLock条件锁
static NSConditionLock *cdtLock = nil;
#define A_THREAD 1
#define B_THREAD 2
#define C_THREAD 3
__block NSInteger a = B_THREAD;
if (cdtLock == nil) {
cdtLock = [[NSConditionLock alloc] initWithCondition:a];
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"A thread run!");
BOOL canLock = [cdtLock tryLockWhenCondition:A_THREAD];
if (!canLock) {
NSLog(@"A Thread Lock fail,exit!");
return ;
}
NSLog(@"A thread begin lock!");
[NSThread sleepForTimeInterval:8];
NSLog(@"A thread unlock!");
[cdtLock unlock];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"B thread run!");
BOOL canLock = [cdtLock tryLockWhenCondition:B_THREAD];
if (!canLock) {
NSLog(@"B Thread Lock fail,exit!");
return ;
}
NSLog(@"B thread begin lock!");
[NSThread sleepForTimeInterval:8];
NSLog(@"B thread unlock!");
[cdtLock unlock];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"C thread run!");
BOOL canLock = [cdtLock tryLockWhenCondition:C_THREAD];
if (!canLock) {
NSLog(@"C Thread Lock fail,exit!");
return ;
}
NSLog(@"C thread begin lock!");
[NSThread sleepForTimeInterval:8];
NSLog(@"C thread unlock!");
[cdtLock unlock];
});
- 4.NSRecursiveLock递归锁
static NSRecursiveLock *lock;
if (lock == nil) {
lock = [[NSRecursiveLock alloc] init];
}
void (^__block DoLog)(int) = ^(int value){
[lock lock];
if (value > 0) {
DoLog(value-1);
}
NSLog(@"value is %d", value);
[lock unlock];
};
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"test begin");
DoLog(5);
NSLog(@"test end");
});
网友评论