zoukankan      html  css  js  c++  java
  • 从源码理解 ThreadLocal

    为每个线程保存各自的拷贝,可以通过在Thread类中定义一个成员变量来保存每个线程值,这样也是线程安全的。

    通过定义一个成员变量 sn 来实现,这里并没有使用ThreadLocal类来实现:

    public class Test {
        public static void main(String[] args) {
            SequenceNumber sn = new SequenceNumber();
    
            //③ 3个线程共享sn,各自产生序列号
            TestClient t1 = new TestClient();
            TestClient t2 = new TestClient();
            TestClient t3 = new TestClient();
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
    
    class SequenceNumber {
    
        //①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
        private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {
            public Integer initialValue() {
                return 0;
            }
        };
    
        //②获取下一个序列值
        public int getNextNum() {
            seqNum.set(seqNum.get() + 1);
            return seqNum.get();
        }
    }
    
    
    class TestClient extends Thread {
        private int sn;
    
        public TestClient() {
        }
    
        public void run() {
            //④每个线程打出3个序列值
            for (int i = 0; i < 3; i++) {
                System.out.println("thread[" + Thread.currentThread().getName() +
                        "] sn[" + sn++ + "]");
            }
        }
    }
    View Code

    但为什么要使用ThreadLocal(),有什么好处:

      我的理解是:如果在Thread类中定义一个成员变量,会使Thread类和被调用类之间耦合太深,使用ThreadLocal能解决这种耦合的问题

      

    这里所说的线程安全主要是:

    保证一个单例的完整性;

    线程上下文中的变量传递问题,一致性;

    可参考:

    ThreadLocal和synchronized的区别?

    ThreadLocal使用场景

    源码待完成...

  • 相关阅读:
    【习题 8-9 1613】 K-Graph Oddity
    【习题 8-8 UVA
    【Hello 2018 D】Too Easy Problems
    【Hello 2018 C】Party Lemonade
    【Hello 2018 B】Christmas Spruce
    【Hello 2018 A】 Modular Exponentiation
    【习题 8-7 UVA
    【习题 8-6 UVA
    【习题 8-4 UVA
    【习题 8-3 UVA
  • 原文地址:https://www.cnblogs.com/mzzcy/p/7056888.html
Copyright © 2011-2022 走看看