标签:
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
- (void)create_thread_first{ NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"create_thread_first"]; thread.name = @"线程名字"; [thread start]; }
- (void)download:(NSString *)url{ // [NSThread sleepForTimeInterval:5];//休眠五秒 // // NSDate * date = [NSDate dateWithTimeIntervalSinceNow:3];//休眠3秒 // [NSThread sleepUntilDate:date]; NSLog(@"%@--%@",url,[NSThread currentThread]); }
- (void)create_thread_second{ [self performSelectorInBackground:@selector(download:) withObject:@"create_thread_second"]; }
- (void)create_thread_third{ [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"create_thread_third"]; }
- (void)thread_safety{ self.leftCount = 50; self.threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; self.threadOne.name = @"threadOne"; self.threadTwo = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; self.threadTwo.name = @"threadTwo"; self.threadThree = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; self.threadThree.name = @"threadThree"; [self.threadOne start]; [self.threadTwo start]; [self.threadThree start]; } - (void)saleTicket{ while (1) { @synchronized(self) {//加锁,保证线程安全 if (self.leftCount > 0) { self.leftCount --; NSLog(@"%@卖了一张票,剩余%d张票",[NSThread currentThread].name,self.leftCount); }else{ return;//退出线程 } } } }
标签:
原文地址:http://blog.csdn.net/fuzongjian/article/details/51333950