ThreadLocal(線程局部變量)

單從字面翻譯更應該是本地化線程,而後倒是線程局部變量(ThreadLocalVariable)不是更合適嗎?java

ThreadLocal究竟是用來幹什麼的喃?固然是保存線程私有的數據啊,因此一般變量是被修飾爲private的。與局部變量不一樣,一般是被定義爲所有變量,而後它爲全部線程都維護一份私有數據,具體實現方式就是爲每個線程維護一個用Entity數組實現的Map數組

public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
}

線程局部變量和線程共享數據區別在於一個用空間換時間,一個用時間換空間。後者用同步進行排隊訪問,而前者由於是獨自維護的,不涉及同步問題ide

舉例:this

package com.jv.java8.datetime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.junit.Test;

public class TestDateTime {

	
	@Test
	public void test1() {
		ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
			
			protected SimpleDateFormat initialValue() {
				
				return new SimpleDateFormat("yyyyMMdd");
			}
			
		};
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		
		Callable<Date> task = new Callable<Date>() {

			@Override
			public Date call() throws Exception {
				return sdf.get().parse("2018228");
			}
			
			
		};
		
		ExecutorService pool = Executors.newFixedThreadPool(5);
		
		List<Future<Date>> results = new ArrayList<>();
		for(int i=0;i<10;i++) {
			results.add(pool.submit(task));
		}
		
		results.stream().map(x->{
			try {
				return x.get();
			} catch (Exception e) {
			}
			return null;
		}).forEach(System.out::println);
	}
}

對於代碼中使用的Lambda表達式能夠Java-Lambda表達式.net

對於設計的局部變量類型須要注意僞共享問題,能夠參考僞共享線程

相關文章
相關標籤/搜索