先釐清兩個常被混用的名詞。進程(Process)是系統分配資源的最小單位;線程(Thread)是程式執行的最小單位。一個進程可包含多個線程,同一進程內的線程共享相同的記憶體空間,而各進程的位址空間彼此獨立。在 iOS 上,更新 UI 只能由主線程(主進程)進行,工作線程則需手動開啟。
以下用經典的「多線程售票」範例說明:三個子線程同時賣 100 張票,透過 NSCondition 避免重複賣出同一張。
@interface LinViewController : UIViewController {
int _leftTickets; // 剩餘票數
int _soldTickets; // 已售票數
NSThread *_firstThread;
NSThread *_secondThread;
NSThread *_thridThread;
NSCondition *_ticketsCondition; // 線程鎖
}
@property (retain, nonatomic) UILabel *leftLabel;
@property (retain, nonatomic) UILabel *soldLabel;
@property (retain, nonatomic) UILabel *currentThreadLabel;
@end
#import "LinViewController.h"
// 預先定義總票數
#define MaxTickets 100
@implementation LinViewController
- (void)dealloc {
[_leftLabel release];
[_soldLabel release];
[_currentThreadLabel release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self addLabel:nil]; // 加入輔助說明標籤
self.leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 90, 100, 30)];
self.soldLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 170, 100, 30)];
self.currentThreadLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 250, 100, 30)];
self.leftLabel.backgroundColor = [UIColor lightGrayColor];
self.soldLabel.backgroundColor = [UIColor lightGrayColor];
self.currentThreadLabel.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:self.leftLabel];
[self.view addSubview:self.soldLabel];
[self.view addSubview:self.currentThreadLabel];
_leftTickets = MaxTickets;
_soldTickets = 0;
_ticketsCondition = [[NSCondition alloc] init];
UIButton *pButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[pButton setFrame:CGRectMake(80, 340, 180, 40)];
[pButton setTitle:@"開始賣票" forState:UIControlStateNormal];
[pButton addTarget:self action:@selector(threadStart:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pButton];
}
#pragma mark ----- 加入輔助標籤 -----
- (void)addLabel:(id)sender {
UILabel *pLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 40)];
UILabel *pLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 120, 50)];
UILabel *pLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 160, 120, 50)];
UILabel *pLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(10, 240, 120, 50)];
pLabel.text = @"模擬火車票銷售---多線程";
pLabel1.text = @"剩餘票數";
pLabel2.text = @"售出票數";
pLabel3.text = @"當前線程";
pLabel.backgroundColor = [UIColor clearColor];
pLabel1.backgroundColor = [UIColor clearColor];
pLabel2.backgroundColor = [UIColor clearColor];
pLabel3.backgroundColor = [UIColor clearColor];
pLabel.textAlignment = NSTextAlignmentCenter;
pLabel1.textAlignment = NSTextAlignmentCenter;
pLabel2.textAlignment = NSTextAlignmentCenter;
pLabel3.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:pLabel];
[self.view addSubview:pLabel1];
[self.view addSubview:pLabel2];
[self.view addSubview:pLabel3];
[pLabel release];
[pLabel1 release];
[pLabel2 release];
[pLabel3 release];
}
#pragma mark ----- 開始賣票 -----
- (void)threadStart:(id)sender {
_firstThread = [[NSThread alloc] initWithTarget:self
selector:@selector(sellTickets:)
object:nil];
[_firstThread setName:@"thread-1"];
[_firstThread start]; // 必須手動開啟
_secondThread = [[NSThread alloc] initWithTarget:self
selector:@selector(sellTickets:)
object:nil];
[_secondThread setName:@"thread-2"];
[_secondThread start];
_thridThread = [[NSThread alloc] initWithTarget:self
selector:@selector(sellTickets:)
object:nil];
[_thridThread setName:@"thread-3"];
[_thridThread start];
}
// 賣票邏輯
- (void)sellTickets:(id)sender {
while (YES) {
[_ticketsCondition lock]; // 上鎖,避免同一張票被重複賣出
if (_leftTickets > 0) {
[NSThread sleepForTimeInterval:0.1]; // 模擬耗時
_leftTickets--;
_soldTickets = MaxTickets - _leftTickets;
} else if (_leftTickets == 0) {
NSLog(@"票已經賣完!");
break;
}
// 只有主線程能更新 UI,因此把更新丟回主線程
[self performSelectorOnMainThread:@selector(updateMyView:)
withObject:[[NSThread currentThread] name]
waitUntilDone:YES];
NSLog(@"剩餘票數:%i 售出票數:%i 當前線程%@",
_leftTickets, _soldTickets, [[NSThread currentThread] name]);
[_ticketsCondition unlock];
}
}
#pragma mark ----- 更新界面 -----
- (void)updateMyView:(id)sender {
self.leftLabel.text = [NSString stringWithFormat:@"%i", _leftTickets];
self.soldLabel.text = [NSString stringWithFormat:@"%i", _soldTickets];
self.currentThreadLabel.text = (NSString *)sender;
if (_leftTickets == 0) {
UIAlertView *pAlertView = [[UIAlertView alloc] initWithTitle:@"溫馨提示"
message:@"票已經全部售出!"
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil, nil];
[pAlertView show];
[pAlertView release];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
三個值得記住的結論:NSThread 建立後必須呼叫 start 才會真正執行;子線程不能直接碰 UI,必須用 performSelectorOnMainThread: 轉回主線程;共享計量器一定要用鎖保護,否則 sleep 造成的時序交錯會讓票數憑空多出或減少。順帶一提,程式中的 break 發生在 lock 之後,實務上應改用 @synchronized 或確保解鎖路徑完整,這類細節正是多線程 bug 的溫床。