首先创建一个num类,该类的成员用于线程同步。 public class Num { int i; boolean falg; } 1. 2. 3. 4. 使用wait/notify机制+条件判断实现 public class TestThread1 { public static void main(String[] args) { Num num=new Num(); Thread t1=new Thread(new A(num)); Thread t2=new Thread(ne...
使用两个线程交替打印奇偶数,需要用到锁来实现,下边有3种实现方式: 使用NSLock实现 NSLock *lock = [[NSLock alloc] init]; __block int number = 0; dispatch_async(queue1, ^{ while (number < 100) { [lock lock]; if (number%2 == 0) { number++; NSLog(@"奇数---%d",number); } [...
package mianTest; // 单纯的利用boolean变量来写 加一个volatile关键字:保证他的可见性 public class Demo01 { volatile static int flag = 0; public static void main(String[] args) { Thread myThread = new Thread(new myThread1()); Thread myThread2 = new Thread(new myThread2()); myThread.s...