方法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.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();
}