Volatile可见性及非原子性验证

1.测试(可见性)

1.1 代码

public class JMMTest {
    
    
	private static int num = 0;

	public static void main(String[] args) {
    
    
		new Thread(()->{
    
    
			while (num==0) {
    
    
				
			}
		}).start();
		
		try {
    
    
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
    
    
			e.printStackTrace();
		}
		
		//已经变成1了,但是程序没有停止
		num = 1;
		System.out.println(num);
	}
}

在这里插入图片描述

1.2 结果

在这里插入图片描述

1.3 加入 volatile修饰后

在这里插入图片描述

2. 测试(不保证原子性)

2.1 代码

public class JMMTest2 {
    
    
	//加入volatile
	private static int num = 0;
	
	public static void add() {
    
    
		num++;
	}

	public static void main(String[] args) {
    
    
		for (int i = 0; i < 20; i++) {
    
    
			new Thread(()->{
    
    
				for (int j = 0; j < 1000; j++) {
    
    
					
					add();
				}
			}).start();
		}
		
		while (Thread.activeCount()>2) {
    
    
			Thread.yield();
		}

		System.out.println(num);
	}
}

在这里插入图片描述
加入synchronized后
在这里插入图片描述

2.2 加入volatile 不能保证原子性

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jj89929665/article/details/113050680