售票模擬多個執行緒搶奪同一塊資源問題

2022-01-11 10:46:53 字數 1081 閱讀 2819

用執行緒代表不同售票視窗,用執行緒執行的方法模擬售票。如果不加鎖,會出現多個售票視窗同時售一張票的情況。

@property (nonatomic, strong) nsthread *thread1;

@property (nonatomic, strong) nsthread *thread2;

@property (nonatomic, strong) nsthread *thread3;

/** * 剩餘票數

*/@property (nonatomic, assign) int leftticketcount;

self.leftticketcount = 50;

self.thread1 = [[nsthread alloc] initwithtarget:self selector:@selector(saleticket) object:nil];

self.thread1.name = @"1號視窗";

self.thread2 = [[nsthread alloc] initwithtarget:self selector:@selector(saleticket) object:nil];

self.thread2.name = @"2號視窗";

self.thread3 = [[nsthread alloc] initwithtarget:self selector:@selector(saleticket) object:nil];

self.thread3.name = @"3號視窗";

//開售

[self.thread1 start];

[self.thread2 start];

[self.thread3 start];

/**

* 賣票 加鎖了就不會出現執行緒安全問題

* 不加鎖就會出問題

*/- (void)saleticket

else

} // 解鎖

}}

另外,加鎖是消耗cpu資源的,盡量將加鎖,資源搶奪的業務邏輯交給伺服器端處理,減小移動端的壓力。

模擬多人售票的多執行緒測試

01classlockdemocatch exception e 06 07tt.lockname vip clinet1 saler b was late for work,but 08 later is better than never 09newthread tt start 10 11 1...

模擬多執行緒

用兩個執行緒玩猜數字遊戲,第乙個執行緒負責隨機給出1 100之間的乙個整數,第二個執行緒負責猜出這個數。要求每當第二個執行緒給出自己的猜測後,第乙個執行緒都會提示 猜小了 猜大了 或 猜對了 猜數之前,要求第二個執行緒要等待第乙個執行緒設定好要猜測的數。第乙個執行緒設定好猜測數之後,兩個執行緒還要相...

curl模擬多執行緒

開啟會話 設定會話引數 傳送請求 關閉控制代碼 請求鏈結 arr foreach arr as key url 執行curl會話 res curl exec ch 關閉curl會話並釋放資源 curl close ch 指令碼開始的毫秒時刻 start microtime true 鏈結陣列 arr...