ThreadLocal並不是一個Thread,而是Thread的
局部變量,也許把它命名為ThreadLocalVariable更容易讓人理解一些。
所以,在Java中編寫線程局部變量的代碼相對來說要笨拙一些,因此造成線程局部變量沒有在Java開發者中得到很好的普及。
ThreadLocal的接口方法
ThreadLocal類接口很簡單,只有4個方法,我們先來了解一下:
void set(Object value)
public void remove()
將當前線程
局部變量的值刪除,目的是為了減少內存的占用。
ThreadLocal的原理
在ThreadLocal類中有一個Map,用於
存儲每一個線程的變量的副本。比如下面的示例實現:
public class ThreadLocal
private Map values = Collections.synchronizedMap(new HashMap());
public Object get()
{
Thread curThread = Thread.currentThread();
Object o = values.get(curThread);
if (o == null && !values.containsKey(curThread))
{
o = initialValue();
values.put(curThread, o);
}
values.put(Thread.currentThread(), newValue);
return o ;
}
public Object initialValue()
{
return null;
}
}
演示代碼
public class ThreadLocalExample { public static class MyRunnable implements Runnable { private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(); int local = 0; @Override public void run() { threadLocal.set((int) (Math.random() * 100D)); local = (int) (Math.random() * 100D); try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("threadLocal:" +threadLocal.get()); System.out.println("local:" +local); } } public static void main(String[] args) { MyRunnable sharedRunnableInstance = new MyRunnable(); Thread thread1 = new Thread(sharedRunnableInstance); Thread thread2 = new Thread(sharedRunnableInstance); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // wait for thread 1 to terminate // wait for thread 2 to terminate } }