ThreadLocal

  1. public class SequenceNumber {  
  2.        
  3.         //①通過匿名內部類覆蓋ThreadLocal的initialValue()方法,指定初始值  
  4.     private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){  
  5.         public Integer initialValue(){  
  6.             return 0;  
  7.         }  
  8.     };  
  9.        
  10.         //②獲取下一個序列值  
  11.     public int getNextNum(){  
  12.         seqNum.set(seqNum.get()+1);  
  13.         return seqNum.get();  
  14.     }  
  15.       
  16.     public static void main(String[ ] args)   
  17.     {  
  18.           SequenceNumber sn = new SequenceNumber();  
  19.            
  20.          //③ 3個線程共享sn,各自產生序列號  
  21.          TestClient t1 = new TestClient(sn);    
  22.          TestClient t2 = new TestClient(sn);  
  23.          TestClient t3 = new TestClient(sn);  
  24.          t1.start();  
  25.          t2.start();  
  26.          t3.start();  
  27.     }     
  28.     private static class TestClient extends Thread  
  29.     {  
  30.         private SequenceNumber sn;  
  31.         public TestClient(SequenceNumber sn) {  
  32.             this.sn = sn;  
  33.         }  
  34.         public void run()  
  35.         {  
  36.                         //④每個線程打出3個序列值  
  37.             for (int i = 0; i < 3; i++) {  
  38.             System.out.println("thread["+Thread.currentThread().getName()+  
  39. "] sn["+sn.getNextNum()+"]");  
  40.             }  
  41.         }  
  42.     }  
  43. }  


  1. public class TopicDao {  
  2.   
  3.   //①使用ThreadLocal保存Connection變量  
  4. private static ThreadLocal<Connection> connThreadLocal = new ThreadLocal<Connection>();  
  5. public static Connection getConnection(){  
  6.            
  7.         //②如果connThreadLocal沒有本線程對應的Connection創建一個新的Connection,  
  8.         //並將其保存到線程本地變量中。  
  9. if (connThreadLocal.get() == null) {  
  10.             Connection conn = ConnectionManager.getConnection();  
  11.             connThreadLocal.set(conn);  
  12.               return conn;  
  13.         }else{  
  14.               //③直接返回線程本地變量  
  15.             return connThreadLocal.get();  
  16.         }  
  17.     }  
  18.     public void addTopic() {  
  19.   
  20.         //④從ThreadLocal中獲取線程對應的  
  21.          Statement stat = getConnection().createStatement();  
  22.     }  
  23. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章