首页 > 代码库 > ThreadLocal

ThreadLocal

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

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