日期:2014-05-20 浏览次数:20754 次
package net.xinxin.test; public class testThreadLocal { protected BankAccount account; public testThreadLocal(BankAccount account) { this.account = account; } private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){ public Integer initialValue(){ return 0; } }; private ThreadLocal<Integer> accountNum = new ThreadLocal<Integer>(){ public Integer initialValue(){ return account.getBalance(); } }; public int getNextNum(){ seqNum.set(seqNum.get()+1); return seqNum.get(); } private int getAccountNum() { accountNum.set(accountNum.get()+10); return accountNum.get(); } private static class TestClient extends Thread{ private testThreadLocal ttl; public TestClient(testThreadLocal ttl) { this.ttl=ttl; } public void run(){ for(int i=0;i<3;i++){ ttl.getAccountNum(); System.out.println("thread["+Thread.currentThread().getName()+"] sn["+ttl.getNextNum()+"]");//注释编号1:若在这里打印accountNum.get(),值是期望的 } } } public static void main(String[] args)throws Exception{ BankAccount a = new BankAccount(1,100); testThreadLocal ttl = new testThreadLocal(a); TestClient t1 = new TestClient(ttl); TestClient t2 = new TestClient(ttl); TestClient t3 = new TestClient(ttl); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); System.out.println(ttl.accountNum.get());//注释编号2:这里打印仅有第一次结果 } }