java volatile 使用demo

Java

2017-06-27

372

0

技术:java8内存模型 demo

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

demo功能:提供一个使用 volatile关键字的代码demo

volatile线程安全demo:http://demoworld.tech/c/java_volatile_muti_thread_demo

保证对全部线程的数据可见性。线程A修改了没有使用volatile修饰的变量值, 其他线程不能使用修改后的最新的值

  private static boolean flag1 = false;

    //当变量没有使用volatile修饰时, 其他线程对变量的值进行修改, 这个线程看不到修改后的值。 很多情况我们是希望其他线程也可以看到
    @Test
    public void testAccessableForAllThreads1() throws InterruptedException {
        new Thread() {
            int i = 0;
            @Override
            public void run() {
                while (!flag1) {
                    i++;
                    i--;
                }
                //如果这个线程可以看到flag2被其他线程修改后的值,
                 // 就会跳出while, 执行下面的语句。 这个测试用例不会执行
                System.out.println("i can see other threads change flag's value using volatile varables");
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    flag1 = true;
                    System.out.println("i changed flag's value to true, can any thread see it?");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        System.out.println("wait all thrads over...");
        Thread.sleep(99999);
    }

保证对全部线程的数据可见性。线程A修改了使用volatile修饰的变量值, 其他线程能使用修改后的最新的值

 private static volatile boolean flag2 = false;

    //当变量使用volatile修饰时, 其他线程对变量的值进行修改, 这个线程可以看到修改后的值。 符合我们的预期
    @Test
    public void testAccessableForAllThreads2() throws InterruptedException {
        new Thread() {
            int i = 0;

            @Override
            public void run() {
                while (!flag2) {
                    i++;
                    i--;
                }
                //如果这个线程可以看到flag2被其他线程修改后的值,
// 就会跳出while, 执行下面的语句。 这个测试用例会执行的。 符合我们的预期
                System.out.println("i can see other threads change flag's value using volatile varables");
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    flag2 = true;
                    System.out.println("i changed flag's value to true, can any thread see it?");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        System.out.println("wait all thrads over...");
        Thread.sleep(99999);
    }

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

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think