1. 程式人生 > >多執行緒學習六——ThreadLocal的使用

多執行緒學習六——ThreadLocal的使用

package day1;

import java.util.HashMap;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class ThreadLocalTest {
    static CyclicBarrier c = new CyclicBarrier(2);
    private ThreadLocal<HashMap<String,String>> mapLocal = new
ThreadLocal<HashMap<String,String>>(){ @Override protected HashMap<String,String> initialValue() { return new HashMap<String,String>(); } }; private HashMap<String,String> hashMap= new HashMap<String,String>(); public
void put(String key,String value) { HashMap<String,String> hashMap = mapLocal.get(); if(hashMap == null) { System.out.println("======="); hashMap = new HashMap<String,String>(); } hashMap.put(key, value); mapLocal.set(hashMap); } public
String get(String key) { return mapLocal.get().get(key); } public HashMap<String, String> getHashMap() { return hashMap; } public void setHashMap(HashMap<String, String> hashMap) { this.hashMap = hashMap; } public static void main(String[] args) throws Exception { ThreadLocalTest profiler=new ThreadLocalTest(); for(int i =0;i<6;i++) { new Thread("thread"+i) { public void run() { try { c.await(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (BrokenBarrierException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } profiler.put("name", Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+":" +profiler.get("name")); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } for(int i =6;i<12;i++) { new Thread("thread"+i) { public void run() { try { c.await(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (BrokenBarrierException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } profiler.getHashMap().put("name", Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()+":" +profiler.getHashMap().get("name")); } }.start(); } } }

console輸出:

thread8:thread9
thread9:thread9
thread6:thread11
thread10:thread11
thread11:thread11
thread0:thread0
thread1:thread1
thread2:thread2
thread4:thread4
thread3:thread3
thread7:thread7
thread5:thread5

執行緒0-5中的name的值跟執行緒名是一一對應的,6-11則每次執行的時候都會不一樣,所以ThreadLocal可用於保證執行緒安全,每個執行緒都保有一個ThreadLocal