区别
https://www.zhihu.com/question/41579791
一些有关于volatile的文章
http://www.cnblogs.com/xrq730/p/7048693.html
http://blog.csdn.net/yechaodechuntian/article/details/26009363
http://www.cnblogs.com/zemliu/p/3298685.html
单例模式中的volatile
http://jiangzhengjun.iteye.com/blog/652440
http://blog.csdn.net/anjxue/article/details/51038466
java6下执行 ( java8下会无论加不加volatile都会退出循环)
public static void main(String[] args) throws InterruptedException { RunningThread runningThread = new RunningThread(); runningThread.start(); VolatileRunningThread volatileRunningThread = new VolatileRunningThread(); volatileRunningThread.start(); Thread.sleep(1000); runningThread.isRunning = false; volatileRunningThread.isRunning = false; } static class RunningThread extends Thread { public Boolean isRunning; int i = 0; // 改成Integer会退出循环 不知道为什么? @Override public void run() { isRunning = true; while (isRunning) { i++; } System.out.println(i); System.out.println("RunningThread退出循环 isRunning=" + isRunning); } } static class VolatileRunningThread extends Thread { public volatile Boolean isRunning; @Override public void run() { isRunning = true; while (isRunning) { ; } System.out.println("VolatileRunningThread退出循环 isRunning=" + isRunning); } }
public class TestVolatile extends Thread{ static int i = 0; private static boolean stopRequested; @Override public void run() { for (int j = 0; j < 100000; j++) { i++; } } public static void main(String[] args) throws InterruptedException { dsa(); } private static void aaa() throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!stopRequested) { i++; } } }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; } /** * 使用volatile修饰i 输出2809657 * 使用static修饰i或者不修饰i 输出4701547 * */ private static void dsa() { TestVolatile testVolatile = new TestVolatile(); List<Thread> list = new ArrayList<Thread>(); for (int i = 0; i < 100; i++) { Thread thread = new Thread(testVolatile); list.add(thread); } for (Thread thread : list) thread.start(); f:for (;;) { for (Thread thread : list ) if (thread.isAlive()) continue f; break; } System.out.println(testVolatile.i); } }