zoukankan      html  css  js  c++  java
  • NSLock简单应用

     1 #import "AppDelegate.h"
     2 
     3 @interface AppDelegate ()
     4 
     5 @end
     6 
     7 @implementation AppDelegate
     8 
     9 -(void)dealloc{
    10     
    11     [_window release];
    12     [super dealloc];
    13 }
    14 
    15 
    16 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    17     self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    18     self.window.backgroundColor = [UIColor blackColor];
    19     
    20     [self.window makeKeyAndVisible];
    21     
    22     [_window release];
    23     
    24     //线程互斥  线程没有自己独立的栈堆空间,都是使用进程内部的内存空间,所以有可能多个线程同时访问同一块内存,这时就会出问题,针对多线程访问共享资源是就会采用线程互斥方式,加线程锁
    25     NSLock *lk = [[NSLock alloc]init];
    26     
    27     NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(therad:) object:lk];
    28     
    29     thread1.name = @"1号窗口";
    30     
    31     [thread1 start];
    32     
    33     
    34     
    35     NSThread *therad2 = [[NSThread alloc]initWithTarget:self selector:@selector(therad:) object:lk];
    36     
    37     therad2.name = @"2号窗口" ;
    38     
    39 //    therad2.threadPriority = 0.9 ;
    40     
    41     [therad2 start];
    42     
    43     
    44     
    45     NSThread *therad3 = [[NSThread alloc]initWithTarget:self selector:@selector(therad:) object:lk];
    46     
    47     therad3.name = @"3号窗口" ;
    48     
    49     therad3.threadPriority = 1 ;
    50     
    51     [therad3 start];
    52     
    53     
    54     
    55     
    56     
    57     
    58     return YES;
    59 }
    60 
    61 
    62 //模拟售票
    63 -(void)therad:(id)object{
    64     
    65     NSLock *lk = (NSLock *)object ;
    66     
    67     //票数100张
    68     static int number = 100 ;
    69     
    70     while (1) {
    71         
    72         // 加线程锁,提高数据访问的安全性
    73         [lk lock];
    74         
    75         number -- ;
    76         
    77         NSLog(@"%@ %d",[[NSThread currentThread]name],number);
    78         
    79           //休眠1秒
    80         sleep(1);
    81         
    82         if (number == 0) {
    83             break ;
    84         }
    85         
    86         [lk unlock] ;
    87     }
    88     
    89 }
  • 相关阅读:
    实现tip浮层
    c++实现冒泡排序
    一天一小段js代码(no.4)
    html5 css3实现图中结构
    html表格相关
    js跨浏览器的事件处理函数
    js实现DOM结构
    CSS3实现鼠标移动到图片上图片变大(缓慢变大,有过渡效果,放大的过程是有动画过渡的,这个过渡的时间可以自定义)
    正则表达式学习笔记
    使用JS与CSS3的翻转实现3D翻牌效果
  • 原文地址:https://www.cnblogs.com/yyxblogs/p/4878926.html
Copyright © 2011-2022 走看看