我们先看一下线程状态
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}
- (void)run{
for (NSInteger i = 0; i < 100; i++) {
NSLog(@"--------%zd",i);
if (i == 49) {
//break;也可以
[NSThread exit];//直接退出线程
}
}
}
- (void)run2{
NSLog(@"dascsadas");
NSLog(@"______%@",[NSDate distantFuture]);
// [NSThread sleepForTimeInterval:3];//让线程睡3秒。
// [NSThread sleepUntilDate:[NSDate distantFuture]];//遥远的未来。打印了第一个第二个,第三个不打印
// [NSThread sleepUntilDate:[NSDate distantPast]];//过去
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];//睡3秒
NSLog(@"dascsadas");
}
接下来是同步线程,线程锁
/** 售票员01 */
@property (nonatomic,strong)NSThread *thread01;
/** 售票员02 */
@property (nonatomic,strong)NSThread *thread02;
/** 售票员03 */
@property (nonatomic,strong)NSThread *thread03;
/** 票总数 */
@property (nonatomic,assign)NSInteger ticketCount;
@property (nonatomic,strong)NSObject *locker;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.locker = [[NSObject alloc]init];
self.ticketCount = 1000;
self.thread01 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil
];
self.thread01.name = @"1";
self.thread02 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil
];
self.thread02.name = @"2";
self.thread03 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil
];
self.thread03.name = @"3";
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.thread01 start];
[self.thread02 start];
[self.thread03 start];
}
- (void)saleTicket{
// NSObject *obj = [[NSObject alloc]init];
while (1) {
// thread1 先进来 先加一把锁 所以 @synchronized([[NSObject alloc]init]) 这必须写[[NSObject alloc]init]
// thread2 可能会进来 所以得用同一把锁
// [self.thread01 start];
// [self.thread02 start];
// [self.thread03 start];
//因为每回都 start 每回都在创建,他们只能用同一把锁,所以 @synchronized(self.locker) {
@synchronized(self.locker) {
NSInteger count = self.ticketCount;
if (count>0) {
self.ticketCount = count -1;
NSLog(@"%@卖了一张,还剩下%zd张",[NSThread currentThread].name,self.ticketCount);
}
else{
NSLog(@"票完");
break;
}
}
}
// @synchronized(锁对象) {线程同步技术
//需要锁定代码
// 锁定一份代码只用1把锁,用多把锁是无效的
// 互斥锁的优缺点
// 优点:能有效防止因多线程抢夺资源的数据安全问题
// 缺点:需要消耗大量的CPU资源
// 互斥锁的使用前提:多条线程抢夺同一块资源。同一线程访问同一个变量,需要加锁
// }
// 同步:多条线程在同一条上执行,(按顺序的执行任务)
// 互斥锁:就是使用线程同步技术
}