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 }

 

posted @ 2015-10-14 21:25  YX祥  阅读(597)  评论(0编辑  收藏  举报