· 启动线程
- (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;
}
}
}
}