zoukankan      html  css  js  c++  java
  • 死锁-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

    死锁示例如上

    时光见证了成长,还很无知,我想一点点幼稚转为有知!
  • 相关阅读:
    网络流与线性规划24题 之 餐巾计划问题
    待刷题目分类(一)
    bzoj1787 [Ahoi2008]Meet 紧急集合
    Hoj2634 How to earn more?
    poj3281 Dining
    浅谈数论(三)水仙花数
    poj1637 Sightseeing tour
    动态规划的思考(1)
    网络流-最大流问题 ISAP 算法解释(转自Renfei Song's Blog)
    poj1273 Drainage Ditches
  • 原文地址:https://www.cnblogs.com/foreveriOS/p/5414920.html
Copyright © 2011-2022 走看看