線程範圍內模組之間共用資料及線程間資料獨立

來源:互聯網
上載者:User

IT程式員開發必備-各類資源下載清單,史上最全IT資源,個人收藏總結。
多個線程訪問共用對象和資料的方式

 1.如果每個線程執行的代碼相同,可以使用同一個Runnable對象,這個Runnable對象中有那個共用資料,例如,買票系統就可以這麼做。
 2.如果每個線程執行的代碼不同,這時候需要用不同的Runnable對象,有如下兩種方式來實現這些Runnable對象之間的資料共用:
     (1)將共用資料封裝在另外一個對象中,然後將這個對象逐一傳遞給各個Runnable對象。每個線程對共用資料的操作方法也分配到那個對象身上去完成,這樣容易實現針對該資料進行的各個操作的互斥和通訊。
    (2)將這些Runnable對象作為某一個類中的內部類,共用資料作為這個外部類中的成員變數,每個線程對共用資料的操作方法也分配給外部類,以便實現對共用資料進行的各個操作的互斥和通訊,作為內部類的各個Runnable對象調用外部類的這些方法。
   (3)上面兩種方式的組合:將共用資料封裝在另外一個對象中,每個線程對共用資料的操作方法也分配到那個對象身上去完成,對象作為這個外部類中的成員變數或方法中的局部變數,每個線程的Runnable對象作為外部類中的成員內部類或局部內部類。
   (4)總之,要同步互斥的幾段代碼最好是分別放在幾個獨立的方法中,這些方法再放在同一個類中,這樣比較容易實現它們之間的同步互斥和通訊。
 3.極端且簡單的方式,即在任意一個類中定義一個static的變數,這將被所有線程共用。

例子程式:

package edu.review;import java.util.HashMap;import java.util.Map;import java.util.Random;/** * 題目要求:構造兩線程,要求: *    (1)兩線程並行作業  (這就要求不能使用syschronized關鍵字) *    (2)要求兩線程分別訪問各自的資料data,互不干擾(可以使用Map集合,以Thread.currentThread()作為key,以data作為value) *    (3)線程內有A、B兩個模組,模組之間共用資料data  **/public class Thread2ThreadDataIndependent {     static Map<Thread,Integer> threadMap = new HashMap<Thread, Integer>();public static void main(String[] args) {for (int i = 0; i < 2; i++) {new Thread(new Runnable() {@Overridepublic void run() {int data = new Random().nextInt(); //這裡的data必須定義為局部變數,否則線程間不能實現資料獨立System.out.println(Thread.currentThread().getName()+" has put data: "+data);threadMap.put(Thread.currentThread(), data);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadMap.get(Thread.currentThread());System.out.println("A from "+Thread.currentThread().getName()+" get data :"+data);}}static class B{public void get(){int data = threadMap.get(Thread.currentThread());System.out.println("B from "+Thread.currentThread().getName()+" get data :"+data);}}}



聯繫我們

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