方法1
关于 notify / notifyAll / wait,可参考:
https://www.cnblogs.com/moongeek/p/7631447.html
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
Runnable r = () -> s.jiaocha();
new Thread(r).start();
new Thread(r).start();
Thread.sleep(100000);
}
volatile int i = 0;
private void jiaocha() {
// notify / wait 必须同 synchronized 一起使用,且都是基于同一个对象,本例中为 this
synchronized (this) {
while (i <= 100) {
// 后启动的线程唤醒先启动的线程
// 先启动的线程打印第一条数据
this.notify();
// this.wait() 会释放 synchronized 抢到的锁并不占用 CPU 时间片,直到被另一个线程的 this.notify 唤醒
this.mywait();
System.out.println(Thread.currentThread().getName() + ": " + i);
i++;
}
}
}
private void mywait() {
try {
this.wait();
} catch (Throwable e) {
}
}
}
方法2
volatile boolean flag = false;
private void jiaocha() {
Runnable r1 = () -> {
for (int i = 0; i <= 100; i += 2) {
while (flag) {
continue;
}
System.out.println(Thread.currentThread().getName() + ": " + i);
flag = true;
}
};
Runnable r2 = () -> {
for (int i = 1; i <= 100; i += 2) {
while (!flag) {
continue;
}
System.out.println(Thread.currentThread().getName() + ": " + i);
flag = false;
}
};
new Thread(r1).start();
new Thread(r2).start();
}