码迷,mamicode.com
首页 > 其他好文 > 详细

ThreadLocal

时间:2017-06-17 10:14:46      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:ini   oca   val   eth   turn   style   pre   auto   generated   

它并不是一个线程,而是用来存储变量的,它存储的变量,每个线程都有自己的一份拷贝,每个线程间互不影响

package com.test.thread;

public class ThreadLocalTest {
    private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {

        @Override
        protected Integer initialValue() {
            // TODO Auto-generated method stub
            return 0;
        }
        
    };
    public static void main(String[] args) {
        ThreadLocalTest test = new ThreadLocalTest();
        test.test();
    }
    public void test() {
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    int temp = threadLocal.get();
                    temp ++ ;
                    threadLocal.set(temp);
                    System.out.println(threadLocal.get());
                }
            }).start();;
        }
    }
}

 

ThreadLocal

标签:ini   oca   val   eth   turn   style   pre   auto   generated   

原文地址:http://www.cnblogs.com/heben/p/7032953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!