- iOS实现两个线程交替打印奇数和偶数
```
NSThread*threadA = [[NSThreadalloc]initWithTarget:selfselector:@selector(threadAPrint3)object:nil];
```
NSThread*threadA = [[NSThreadalloc]initWithTarget:selfselector:@selector(threadAPrint3)object:nil];
[threadAstart];
NSThread*threadB = [[NSThreadalloc]initWithTarget:selfselector:@selector(threadBPrint3)object:nil];
[threadBstart];
方法一: 采用两个信号量
// 信号量
- (void)threadAPrint3 {
for(inti =0; i <100; i++) {
dispatch_semaphore_wait(self.sema1, DISPATCH_TIME_FOREVER);
NSLog(@"%d, %@",self.index3, [NSThreadcurrentThread]);
self.index3=self.index3+1;
sleep(1);
dispatch_semaphore_signal(self.sema2);
}
}
// 信号量
- (void)threadBPrint3 {
for(inti =0; i <100; i++) {
dispatch_semaphore_wait(self.sema2, DISPATCH_TIME_FOREVER);
NSLog(@"%d, %@",self.index3, [NSThreadcurrentThread]);
self.index3=self.index3+1;
sleep(1);
dispatch_semaphore_signal(self.sema1);
}
}
方法2: 采用NSCondition
- (void)threadAPrint {
for(inti =0; i <100; i++) {
[self.conditionLocklock];
if((self.index&1) ==1) {
NSLog(@"%d, %@",self.index, [NSThreadcurrentThread]);
[self.conditionLocksignal];
[self.conditionLockwait];
}
self.index=self.index+1;
sleep(1);
[self.conditionLockunlock];
}
}
- (void)threadBPrint {
for(inti =0; i <100; i++) {
[self.conditionLocklock];
if((self.index&1) ==0) {
NSLog(@"%d, %@",self.index, [NSThreadcurrentThread]);
[self.conditionLocksignal];
[self.conditionLockwait];
}
self.index=self.index+1;
sleep(1);
[self.conditionLockunlock];
}
}
方法三: 采用NSConditionLock
- (void)threadAPrint2 {
for(inti =0; i <100; i++) {
[self.conditionLock2 lockWhenCondition:1];
self.index=self.index+1;
NSLog(@"%d, %@",self.index, [NSThreadcurrentThread]);
sleep(1);
[self.conditionLock2 unlockWithCondition:0];
}
}
- (void)threadBPrint2 {
for(inti =0; i <100; i++) {
[self.conditionLock2 lockWhenCondition:0];
self.index=self.index+1;
NSLog(@"%d, %@",self.index, [NSThreadcurrentThread]);
sleep(1);
[self.conditionLock2 unlockWithCondition:1];
}
}