方案一: synchronized + wait/notify 实现
public class TwoThreadPrint {
private static Object object = new Object();
private static boolean isFlag = false;
public static void main(String[] args) {
new Thread(() -> {
for (int i = 1; i <= 99; i += 2) {
synchronized (object) {
if (!isFlag) {
System.out.println("current Thread:" + Thread.currentThread().getName() + ",current i:" + i);
isFlag = true;
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
object.notify();
}
}
}
}, "ThreadA").start();
new Thread(() -> {
for (int i = 2; i <= 100; i += 2) {
synchronized (object) {
if (isFlag) {
System.out.println("current Thread:" + Thread.currentThread().getName() + ",current i:" + i);
isFlag = false;
object.notify();
}
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "ThreadB").start();
}
}
方案二: Lock + Condition 实现
public class TwoThreadPrint2 {
private static Lock lock = new ReentrantLock();
private static Condition condition1 = lock.newCondition();
private static Condition condition2 = lock.newCondition();
public static void main(String[] args) {
new Thread(() -> {
for (int i = 1; i <= 99; i += 2) {
lock.lock();
try {
System.out.println("current Thread:" + Thread.currentThread().getName() + ",current i:" + i);
condition1.await();
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
}, "ThreadA").start();
new Thread(() -> {
for (int i = 2; i <= 100; i += 2) {
lock.lock();
try {
System.out.println("current Thread:" + Thread.currentThread().getName() + ",current i:" + i);
condition1.signal();
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
}, "ThreadB").start();
}
}