ThreadLocal 與 static 變數 

來源:互聯網
上載者:User

 

ThreadLocal是為解決多線程程式的並發問題而提出的,可以稱之為線程局部變數。與一般的變數的區別在於,生命週期是線上程範圍內的。
static變數是的生命週期與類的使用周期相同,即只要類存在,那麼static變數也就存在。
那麼一個 static 的 ThreadLocal會是什麼樣的呢。

看下面一個例子,

 

 

public class SequenceNumber { private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){ public Integer initialValue(){ return 0; } }; public int getNextNum(){ seqNum.set(seqNum.get() + 1); return seqNum.get(); } public static void main(String[] args){ SequenceNumber sn = new SequenceNumber(); TestClient t1 = new TestClient(sn); TestClient t2 = new TestClient(sn); TestClient t3 = new TestClient(sn); t1.start(); t2.start(); t3.start(); t1.print(); t2.print(); t3.print(); } private static class TestClient extends Thread{ private SequenceNumber sn ; public TestClient(SequenceNumber sn ){ this.sn = sn; } public void run(){ for(int i=0; i< 3; i++){ System.out.println( Thread.currentThread().getName() + " --> " + sn.getNextNum()); } } public void print(){ for(int i=0; i< 3; i++){ System.out.println( Thread.currentThread().getName() + " --> " + sn.getNextNum()); } } } }

下面是結果

Thread-2 --> 1 Thread-2 --> 2 Thread-2 --> 3 Thread-0 --> 1 Thread-0 --> 2 Thread-0 --> 3 Thread-1 --> 1 Thread-1 --> 2 Thread-1 --> 3 main --> 1 main --> 2 main --> 3 main --> 4 main --> 5 main --> 6 main --> 7 main --> 8 main --> 9

 

 

可以發現,static的ThreadLocal變數是一個與線程相關的靜態變數,即一個線程內,static變數是被各個執行個體共同引用的,但是不同線程內,static變數是隔開的

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.