zoukankan      html  css  js  c++  java
  • Threadlocal使用Case

    Threadlocal能够为每个线程分配一份单独的副本,使的线程与线程之间能够独立的访问各自副本。Threadlocal 内部维护一个Map,key为线程的名字,value为对应操作的副本。

    /**
     * Created by majun on 16/3/23.
     */
    public class ThreadLocalTest {
        /*
        Threadlocal为每个线程维护一个单独的副本, 线程之间互不影响
         */
        private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
            @Override
            protected Integer initialValue() {
                return 0;
            }
        };
    
        //获取下一个序列值
        public int getNextNum() {
            threadLocal.set(threadLocal.get() + 1);
            return threadLocal.get();
        }
    
        /*
         */
        public static void main(String[] args) {
            ThreadLocalTest threadLocalTest = new ThreadLocalTest();
            Client client1 = new Client(threadLocalTest);
            Client client2 = new Client(threadLocalTest);
            Client client3 = new Client(threadLocalTest);
    
            Thread thread1 = new Thread(client1);
            Thread thread2 = new Thread(client2);
            Thread thread3 = new Thread(client3);
    
            thread1.start();
            thread2.start();
            thread3.start();
    
        }
    
        static class Client implements Runnable {
            private ThreadLocalTest threadLocalTest;
    
            public Client(ThreadLocalTest threadLocalTest) {
                this.threadLocalTest = threadLocalTest;
            }
            public void run() {
                for (int i = 0; i < 3; i++) {
                    System.out.println("thread[" + Thread.currentThread().getName() + "] --> nextNumber=[" +
                            threadLocalTest.getNextNum() + "]");
                }
            }
        }
    }
    
    
    
  • 相关阅读:
    最基础的账户余额要怎么在 mysql 实现?
    跳跃表时间复杂度分析推导
    Redis:RDB 中 fork 的使用
    字段、约束和索引在存储过程中的判断
    高效沟通的基本流程
    人月神话--画蛇添足
    课程评价及加分项
    人月神话--提纲挈领
    热词搜索七
    《大道至简:软件工程实践者的思想》
  • 原文地址:https://www.cnblogs.com/jun-ma/p/5312069.html
Copyright © 2011-2022 走看看