死锁-06-多线程

 1 //
 2 //  ViewController.m
 3 //  07-死锁
 4 //
 5 //  Created by mac on 16/4/20.
 6 //  Copyright © 2016年 mac. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 
11 @interface ViewController ()
12 
13 @end
14 
15 @implementation ViewController {
16     
17     NSObject *_zhangsan;
18     NSObject *_lisi;
19 }
20 
21 - (void)viewDidLoad {
22     [super viewDidLoad];
23     
24     [self addThread];
25 }
26 /**
27  *  创建(wbvf)线程
28  */
29 - (void)addThread {
30     
31     _zhangsan = [[NSObject alloc] init];
32     _lisi = [[NSObject alloc] init];
33     
34     //线程1
35     [NSThread detachNewThreadSelector:@selector(threadAction) toTarget:self withObject:nil];
36     
37     //线程2
38     [NSThread detachNewThreadSelector:@selector(threadAction2) toTarget:self withObject:nil];
39 }
40 - (void)threadAction {
41     
42     //对象级别锁,传递的object作为该锁的唯一标识,只有当标识相同时,才满足互斥条件,另一个线程会阻塞。
43     @synchronized(_zhangsan) {
44         
45         NSLog(@"===zhangge");
46         [NSThread sleepForTimeInterval:1];
47         
48         //尽量不要在一个线程中加多把锁
49 //        @synchronized(_lisi) {
50             NSLog(@"=== lige");
51 //        }
52     }
53 }
54 - (void)threadAction2 {
55     
56     @synchronized(_lisi) {
57         
58         NSLog(@"lige===");
59         [NSThread sleepForTimeInterval:1];
60         
61         @synchronized(_zhangsan) {
62             NSLog(@"zhangge===");
63         }
64     }
65  
66 }
67 @end

死锁示例如上

posted on 2016-04-20 23:19  爱你久久iOS  阅读(153)  评论(0编辑  收藏  举报

导航