原创:转载需注明原创地址 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);
    }
}

运行结果:

Volatile关键字和ThreadLocal变量的简单使用

相关文章:

  • 2022-01-01
  • 2022-01-07
  • 2021-08-23
  • 2021-07-15
  • 2021-09-21
  • 2022-02-17
  • 2021-07-11
  • 2021-07-19
猜你喜欢
  • 2022-12-23
  • 2021-10-09
  • 2021-11-10
  • 2022-12-23
  • 2021-07-13
  • 2021-07-09
相关资源
相似解决方案