· 啓動線程
- (void)start;
· 阻塞線程
+ (void)sleepUntilDate:(NSDate *)date;
- (void)sleepForTimeInterval:(NSTimeInterval *)interval;
· 強制停止線程
+ (void)exit;
注:一旦線程停止(死亡)了,就不能再次開啓任務。
2、多線程的安全隱患
· 資源共享
一塊資源可能會被多個線程共享,即多個線程可能訪問同一塊資源;比如多個線程同時訪問一個對象,這樣就存在安全隱患
3、安全隱患的解決方法--互斥鎖
· 互斥鎖使用格式
@synchronized(鎖對象) {
// 需要鎖定的代碼
}
注意:鎖定一份代碼的鎖必須是同一把鎖才能達到目的
互斥鎖的優缺點:
優點:能有效防止因多線程搶奪資源造成的數據安全問題
缺點:需要消耗大量的CPU資源
互斥鎖的使用前提是:多條線程同時訪問同一資源
互斥鎖也稱線程同步:即多條線程在同一條線上執行(按順序的執行任務)
ViewController.m文件中:
@interface ViewController ()
// 創建4個進程
@property(nonatomic,strong) NSThread *thread1;
@property(nonatomic,strong) NSThread *thread2;
@property(nonatomic,strong) NSThread *thread3;
@property(nonatomic,strong) NSThread *thread4;
@property(nonatomic,assign) NSInteger moneyValue;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化進程
self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney) object:nil];
self.thread1.name = @"路人1";
self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney) object:nil];
self.thread2.name = @"路人2";
self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney) object:nil];
self.thread3.name = @"路人3";
self.thread4 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney) object:nil];
self.thread4.name = @"路人4";
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 啓動進程
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
[self.thread4 start];
}
-(void)takeMoney{
self.moneyValue = 6000;
while (1) {
//互斥鎖
@synchronized(self) {
if (self.moneyValue > 0) {
NSInteger value = self.moneyValue;
self.moneyValue = value - 200;
NSLog(@"%@取錢後,取款機還剩下%ld元",[NSThread currentThread].name,self.moneyValue);
}else {
NSLog(@"取款機沒有餘額了");
break;
}
}
}
}