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 }