Java編程多線程之共享數(shù)據(jù)代碼詳解
本文主要總結(jié)線程共享數(shù)據(jù)的相關(guān)知識,主要包括兩方面:一是某個線程內(nèi)如何共享數(shù)據(jù),保證各個線程的數(shù)據(jù)不交叉;一是多個線程間如何共享數(shù)據(jù),保證數(shù)據(jù)的一致性。
線程范圍內(nèi)共享數(shù)據(jù)
自己實(shí)現(xiàn)的話,是定義一個Map,線程為鍵,數(shù)據(jù)為值,表中的每一項即是為每個線程準(zhǔn)備的數(shù)據(jù),這樣在一個線程中數(shù)據(jù)是一致的。
例子
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 { //準(zhǔn)備一個哈希表,為每個線程準(zhǔn)備數(shù)據(jù) 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類放在數(shù)據(jù)類的內(nèi)部,數(shù)據(jù)類采用單例模式,這樣,新建對象和獲取對象都會更方便,同時封裝性更強(qiáng)。
示例代碼:
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); } } } /** * 將多變量封裝起來的數(shù)據(jù)類 * 單例模式,內(nèi)置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; } }
多線程訪問共享數(shù)據(jù)
幾種方式
- 線程執(zhí)行代碼相同,使用同一Runnable對象,Runnable對象中有共享數(shù)據(jù)
- 線程執(zhí)行代碼不同,將共享數(shù)據(jù)封裝在另一對象中(操作數(shù)據(jù)的方法也在該對象完成),將這個對象逐一傳遞給各個Runnable對象。[本質(zhì):共享數(shù)據(jù)的對象作為參數(shù)傳入Runnable對象]
- 線程執(zhí)行代碼不同,將Runnable對象作為某一個類的內(nèi)部類,共享數(shù)據(jù)作為這個外部類的成員變量(操作數(shù)據(jù)的方法放在外部類)。[本質(zhì):不同內(nèi)部類共享外部類數(shù)據(jù)]
- 結(jié)合上兩種方式,將共享數(shù)據(jù)封裝在另一對象中(操作數(shù)據(jù)的方法也在該對象完成),該對象作為這個外部類的成員變量,將Runnable對象作為內(nèi)部類
最后一種方式的示例:
設(shè)計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(); } } } /** * 將共享數(shù)據(jù)封裝在另一對象中(操作數(shù)據(jù)的方法也在該對象完成) */ 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; } }
總結(jié)
以上就是本文關(guān)于Java編程多線程之共享數(shù)據(jù)代碼詳解的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
上一篇:詳解Java編程規(guī)約(命名風(fēng)格、常量定義、代碼格式)
欄 目:Java編程
下一篇:Java編程迭代地刪除文件夾及其下的所有文件實(shí)例
本文標(biāo)題:Java編程多線程之共享數(shù)據(jù)代碼詳解
本文地址:http://mengdiqiu.com.cn/a1/Javabiancheng/8345.html
您可能感興趣的文章
- 01-10Java咖啡館(1)——嘆咖啡
- 01-10Java Socket編程(三) 服務(wù)器Sockets
- 01-10Java進(jìn)階:Struts多模塊的技巧
- 01-10Java Socket編程(一) Socket傳輸模式
- 01-10Java Socket編程(二) Java面向連接的類
- 01-10Java運(yùn)行時多態(tài)性的實(shí)現(xiàn)
- 01-10Java經(jīng)驗(yàn)點(diǎn)滴:處理沒有被捕獲的異常
- 01-10Java Socket編程(四) 重復(fù)和并發(fā)服務(wù)器
- 01-10Java中的浮點(diǎn)數(shù)分析
- 01-10面向?qū)ο缶幊?Java中的抽象數(shù)據(jù)類型


閱讀排行
本欄相關(guān)
- 01-10Java咖啡館(1)——嘆咖啡
- 01-10JVM的垃圾回收機(jī)制詳解和調(diào)優(yōu)
- 01-10Java Socket編程(三) 服務(wù)器Sockets
- 01-10Java進(jìn)階:Struts多模塊的技巧
- 01-10J2SE 1.5版本的新特性一覽
- 01-10Java Socket編程(一) Socket傳輸模式
- 01-10Java運(yùn)行時多態(tài)性的實(shí)現(xiàn)
- 01-10Java Socket編程(二) Java面向連接的類
- 01-10Java Socket編程(四) 重復(fù)和并發(fā)服務(wù)
- 01-10Java經(jīng)驗(yàn)點(diǎn)滴:處理沒有被捕獲的異常
隨機(jī)閱讀
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10delphi制作wav文件的方法
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10C#中split用法實(shí)例總結(jié)
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 08-05織夢dedecms什么時候用欄目交叉功能?