Volatile关键字和ThreadLocal变量的简单使用
原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11812459.html
package thread; /** * volatile关键字和ThreadLocal变量的使用 */ public class VolatileAndThreadLocal { /** * 基于内存屏障实现的内存可见性关键字修饰的变量 */ private static volatile String PRIVER_KEY = "HELLO WORLD"; static class MyThread extends Thread{ /** * 线程所拥有的私有专属司机 */ private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); @Override public void run() { super.run(); for (int i = 0; i < 3; i++){ threadLocal.set(i); System.out.println(getName() + " threadLocal.get() = " + threadLocal.get()); PRIVER_KEY = "THIS IS MY PRIVER_KEY " + Thread.currentThread().getName() + " INDEX " + i; System.out.println(PRIVER_KEY); } } } public static void main(String[] args){ MyThread myThreadA = new MyThread(); myThreadA.setName("ThreadA"); MyThread myThreadB = new MyThread(); myThreadB.setName("ThreadB"); myThreadA.start(); myThreadB.start(); System.out.println(PRIVER_KEY); } }
运行结果: