今日のMeituan Ermengでこの問題に遭遇しましたが、しばらくの間Faを理解したことを思い出しましたが、私はそれを手動で書きませんでした。
volatileの可視性を使用してスレッドにアクセスし、変更を加えます〜
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.start();
myThread2.start();
}
public static class myThread1 implements Runnable {
@Override
public void run() {
int i = 0;
while (i < 10) {
if (flag == 0) {
System.out.println(Thread.currentThread().getName() + " = " + i);
i += 2;
flag = 1;
}
}
}
}
public static class myThread2 implements Runnable {
@Override
public void run() {
int i = 1;
while (i < 10) {
if (flag == 1) {
System.out.println(Thread.currentThread().getName() + " = " + i);
i += 2;
flag = 0;
}
}
}
}
}