volatile是什么?有什么特点?具体代码例子

volatile就是让变量每次在使用的时候,都从主存中取。而不是从各个线程的“工作内存”,特点:

  1. 可见性;
  2. 禁止指令重排;
  3. 不保证原子性;

volatile可见性代码demo:

Test t = new Test();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "进入线程");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            t.add();
            System.out.println(Thread.currentThread().getName() + t.i);
        }, "A").start();

        while (t.i == 0) {
            //不打印任何东西
        }
        System.out.println(Thread.currentThread().getName() + t.i);

volatile没有原子性:

CountDownLatch latch=new CountDownLatch(100);
        Test t = new Test();
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                t.add2();
                latch.countDown();
            }, "B").start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("unatomity:" + t.i);

解决原子性问题:

AtomicInteger number = new AtomicInteger();
 public void add3() {
        number.getAndIncrement();
    }
CountDownLatch latch=new CountDownLatch(100);
        Test t = new Test();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                t.add3();
                latch.countDown();
            }, "C").start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("atomity:" + t.number);

完整代码DEMO:https://github.com/jav805/javaInterview/blob/master/src/main/java/com/fatboy/demo/VolatileDemo.java

你可能感兴趣的:(volatile是什么?有什么特点?具体代码例子)