1.volatile保证内存可见性
先来看一段代码
package thread;
import java.util.Scanner;
class MyCounter {
public int flag = 0;
}
public class ThreadDemo17 {
public static void main(String[] args) {
MyCounter myCounter = new MyCounter();
Thread t1 = new Thread(() -> {
while (myCounter.flag == 0) {
//什么都不做
}
System.out.println("t1循环结束");
});
Thread t2 = new Thread(() -> {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个人非0整数:");
myCounter.flag = input.nextInt(