• 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() + "]");
                }
            }
        }
    }
    
    
    
  • 相关阅读:
    Hdu1711 Number Sequence--Kmp模板题
    Trie入门--Poj3630 Phone List,查单词,HDU1251 统计前缀,PKU2503 Babelfish
    高次幂的组合数表示形式
    BZOJ1697 [Usaco2007 Feb] Cow Sorting牛排序
    1025 [SCOI2009]游戏(置换群,DP)
    Poj1721 Cards
    [Poi2003]Shuffle
    poj 3128 Leonardo's Notebook(置换的幂)
    POJ3734 Block母函数入门
    重心拉格朗日插值法
  • 原文地址:https://www.cnblogs.com/jun-ma/p/5312069.html
Copyright © 2020-2023  润新知