java volatile muti thread 线程不安全 demo

Java

2017-06-27

255

0

技术:java8内存模型 demo

运行环境:IDEA 15.2 + jdk8 + windows 7

demo功能:提供一个验证 volatile不是线程安全的代码demo 和 怎么使用才能线程安全的demo

volatile使用基本demo: http://demoworld.tech/c/java_volatile_demo1

线程安全:多个线程在访问同一个变量时, 不会有不确定的结果

 

volatile线程不安全的demo

  public static volatile int n = 0;

    public static void increase() {
        n++;
    }

    //这个测试用例,总共是20个线程, 每个限制都加加 10000 次, 最后的结果理论上是 20*10000=200,000
    //但是实际上, 每次的结果都小于理论值。
    @Test
    public void testNotThreadSafe() throws InterruptedException {
        Thread[] tmpThreads = new Thread[20];
        for (int i = 0; i <= tmpThreads.length - 1; i++) {
            tmpThreads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        increase();
                    }
                    System.out.println("Over.");
                }
            });
            tmpThreads[i].start();
        }
        Thread.sleep(2000);
        System.out.println(n);//最后的结果理论上是 20*10000=200,000,
    }

volatile做到线程安全的demo

public static volatile int n = 0;
public synchronized static void increase1() {
	n++;
}

//这个测试用例,总共是20个线程, 每个限制都加加 10000 次, 最后的结果理论上是 20*10000=200,000
//但是实际上, 每次的结果都小于理论值。
@Test
public void testNotThreadSafe1() throws InterruptedException {
	Thread[] tmpThreads = new Thread[20];
	for (int i = 0; i <= tmpThreads.length - 1; i++) {
		tmpThreads[i] = new Thread(new Runnable() {
			@Override
			public void run() {
				for (int j = 0; j < 10000; j++) {
					increase1();
				}
				System.out.println("Over.");
			}
		});
		tmpThreads[i].start();
	}
	Thread.sleep(2000);
	System.out.println(n);//最后的结果理论上是 20*10000=200,000,
}

自己运行下结果看看。 附带java内存模型图

想要了解原因, 请查看源代码注释

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think