Java編程多線程之共用資料代碼詳解,java編程多線程詳解

來源:互聯網
上載者:User

Java編程多線程之共用資料代碼詳解,java編程多線程詳解

本文主要總結線程共用資料的相關知識,主要包括兩方面:一是某個線程內如何共用資料,保證各個線程的資料不交叉;一是多個線程間如何共用資料,保證資料的一致性。

線程範圍內共用資料

自己實現的話,是定義一個Map,線程為鍵,資料為值,表中的每一項即是為每個線程準備的資料,這樣在一個線程中資料是一致的。

例子

package com.iot.thread;import java.util.HashMap;import java.util.Map;import java.util.Random;/** * Created by brian on 2016/2/4. */public class ThreadScopeShareData {//準備一個雜湊表,為每個線程準備資料private static Map<Thread,Integer> threadData = new HashMap<>();public static void main(String[] args) {for (int i=0;i<2;i++){new Thread(          new Runnable() {@Override        public void run() {int data = new Random().nextint();threadData.put(Thread.currentThread(),data);System.out.println(Thread.currentThread()+" put data:"+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()+" get data "+data);}}static class B{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("B from "+Thread.currentThread()+" get data "+data);}}}

上述代碼偶爾會報異常:

Exception in thread "Thread-0" java.lang.NullPointerException
at com.iot.thread.ThreadScopeShareData$A.get(ThreadScopeShareData.java:29)
at com.iot.thread.ThreadScopeShareData$1.run(ThreadScopeShareData.java:21)
at java.lang.Thread.run(Thread.java:745)

具體原因還不知道

ThreadLocal類

API:

java.lang:Class ThreadLocal<T>

  • 單變數

使用ThreadLocal類型的對象代替上面的Map即可

  • 多變數

定義一個對象來封裝多個變數,然後在ThreadLocal中儲存整個對象

多變數時,最好將ThreadLocal類放在資料類的內部,資料類採用單例模式,這樣,建立對象和擷取對象都會更方便,同時封裝性更強。

範例程式碼:
package com.iot.thread;import java.util.Random;/** * Created by brian on 2016/2/4. */public class ThreadLocalTest {private static ThreadLocal<Integer> threadInger = new ThreadLocal<>();public static void main(String[] args) {for (int i=0;i<2;i++){new Thread(new Runnable() {@Override        public void run() {int data = new Random().nextint(100);threadInger.set(data);System.out.println(Thread.currentThread()+" put data:"+data);MyThreadScopeData.getThreadInstance().setName(Thread.currentThread().toString());MyThreadScopeData.getThreadInstance().setAge(data%10);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadInger.get();System.out.println("A from "+Thread.currentThread()+" get data "+data);MyThreadScopeData myThreadScopeData = MyThreadScopeData.getThreadInstance();System.out.println("A from "+myThreadScopeData);}}static class B{public void get(){int data = threadInger.get();System.out.println("B from "+Thread.currentThread()+" get data "+data);MyThreadScopeData myThreadScopeData = MyThreadScopeData.getThreadInstance();System.out.println("B from "+myThreadScopeData);}}}/** * 將多變數封裝起來的資料類 * 單例模式,內建ThreadLocal類型變數 */class MyThreadScopeData{private MyThreadScopeData(){}private static ThreadLocal<MyThreadScopeData> data = new ThreadLocal<>();public static MyThreadScopeData getThreadInstance(){MyThreadScopeData instance = data.get();if(instance == null){instance = new MyThreadScopeData();data.set(instance);}return instance;}private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Override  public String toString() {String reVal = super.toString()+"-{name,age}"+":{"+getName()+","+getAge()+"}";return reVal;}}
多線程訪問共用資料

幾種方式

  • 線程執行代碼相同,使用同一Runnable對象,Runnable對象中有共用資料
  • 線程執行代碼不同,將共用資料封裝在另一對象中(操作資料的方法也在該對象完成),將這個對象逐一傳遞給各個Runnable對象。[本質:共用資料的對象作為參數傳入Runnable對象]
  • 線程執行代碼不同,將Runnable對象作為某一個類的內部類,共用資料作為這個外部類的成員變數(操作資料的方法放在外部類)。[本質:不同內部類共用外部類資料]
  • 結合上兩種方式,將共用資料封裝在另一對象中(操作資料的方法也在該對象完成),該對象作為這個外部類的成員變數,將Runnable對象作為內部類

最後一種方式的樣本:

設計5個線程,其中三個線程每次對j增加1,另外兩個線程對j每次減少1

package com.iot.thread;/** * Created by brian on 2016/2/4. */public class MutiThreadShareData {private static MutiShareData mutiShareData = new MutiShareData();public static void main(String[] args) {for (int i=0;i<3;i++){new Thread(          new Runnable() {@Override            public void run() {System.out.println(Thread.currentThread()+":{j from "+ mutiShareData.getJ()+" + to: "+mutiShareData.increment()+"}");}}).start();}for (int i=0;i<2;i++){new Thread(          new Runnable() {@Override            public void run() {System.out.println(Thread.currentThread()+":{j from "+ mutiShareData.getJ()+" - to: "+mutiShareData.decrement()+"}");}}).start();}}}/** * 將共用資料封裝在另一對象中(操作資料的方法也在該對象完成) */class MutiShareData{private int j = 0;public synchronized int increment(){return ++j;}public synchronized int decrement(){return --j;}public synchronized int getJ() {return j;}public synchronized void setJ(int j) {this.j = j;}}
總結

以上就是本文關於Java編程多線程之共用資料代碼詳解的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

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