Java線程範圍內的共用資料,java線程範圍共用

來源:互聯網
上載者:User

Java線程範圍內的共用資料,java線程範圍共用
線程範圍內的共用資料,在JavaEE中比較常用,Android比較少

一個線程調用A,B,C三個模組,模組中的運算式或變數調用訪問一個資料,這個資料可以是靜態
另一個線程也調用A,B,C三個模組,模組中的運算式或變數訪問的資料,就不是剛才的資料,而是另一個

同樣的代碼,一個線程身上一分資料

import java.util.HashMap;import java.util.Map;import java.util.Random;public class ThreadScopeShareData {private static int data = 0;private static Map<Thread, Integer> threadData = new HashMap<Thread,Integer>();public static void main(String[] args) {for(int i = 0;i<2;i++){new Thread(new Runnable() {public void run() {int data = new Random().nextInt();System.out.println(Thread.currentThread().getName()+" has put data: "+data);threadData.put(Thread.currentThread(),data);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from "+Thread.currentThread().getName()+" get data: "+data);}}static class B{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("B from "+Thread.currentThread().getName()+" get data: "+data);}}}

應用情境:資料庫,一個方法是輸入資料,一個方法是輸出資料,兩個獨立的對象,


A在向B輸入資料,B在向外輸出資料,A->B->


C在向D輸入資料,D在向外輸出資料,C->D->


兩條線共用同一個連結化物件,如果C這條線路結束了,提交結果,那麼不就把A所在的線程中斷了麼,所以每一條線程上操作的都是自己的資料,線程


操作的資料,是自己線程範圍內的資料,與另外線程上的資料無關(銀行轉賬也是如此)


以上執行個體示範了,線程範圍內,(不同模組)資料共用,線程範圍外,資料獨立





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.