Java編程多線程之共享數(shù)據(jù)代碼詳解
本文主要總結(jié)線程共享數(shù)據(jù)的相關(guān)知識(shí),主要包括兩方面:一是某個(gè)線程內(nèi)如何共享數(shù)據(jù),保證各個(gè)線程的數(shù)據(jù)不交叉;一是多個(gè)線程間如何共享數(shù)據(jù),保證數(shù)據(jù)的一致性。
線程范圍內(nèi)共享數(shù)據(jù)
自己實(shí)現(xiàn)的話,是定義一個(gè)Map,線程為鍵,數(shù)據(jù)為值,表中的每一項(xiàng)即是為每個(gè)線程準(zhǔn)備的數(shù)據(jù),這樣在一個(gè)線程中數(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)備一個(gè)哈希表,為每個(gè)線程準(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);
}
}
}
上述代碼偶爾會(huì)報(bào)異常:
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類型的對(duì)象代替上面的Map即可
- 多變量
定義一個(gè)對(duì)象來封裝多個(gè)變量,然后在ThreadLocal中存儲(chǔ)整個(gè)對(duì)象
多變量時(shí),最好將ThreadLocal類放在數(shù)據(jù)類的內(nèi)部,數(shù)據(jù)類采用單例模式,這樣,新建對(duì)象和獲取對(duì)象都會(huì)更方便,同時(shí)封裝性更強(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對(duì)象,Runnable對(duì)象中有共享數(shù)據(jù)
- 線程執(zhí)行代碼不同,將共享數(shù)據(jù)封裝在另一對(duì)象中(操作數(shù)據(jù)的方法也在該對(duì)象完成),將這個(gè)對(duì)象逐一傳遞給各個(gè)Runnable對(duì)象。[本質(zhì):共享數(shù)據(jù)的對(duì)象作為參數(shù)傳入Runnable對(duì)象]
- 線程執(zhí)行代碼不同,將Runnable對(duì)象作為某一個(gè)類的內(nèi)部類,共享數(shù)據(jù)作為這個(gè)外部類的成員變量(操作數(shù)據(jù)的方法放在外部類)。[本質(zhì):不同內(nèi)部類共享外部類數(shù)據(jù)]
- 結(jié)合上兩種方式,將共享數(shù)據(jù)封裝在另一對(duì)象中(操作數(shù)據(jù)的方法也在該對(duì)象完成),該對(duì)象作為這個(gè)外部類的成員變量,將Runnable對(duì)象作為內(nèi)部類
最后一種方式的示例:
設(shè)計(jì)5個(gè)線程,其中三個(gè)線程每次對(duì)j增加1,另外兩個(gè)線程對(duì)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ù)封裝在另一對(duì)象中(操作數(shù)據(jù)的方法也在該對(duì)象完成)
*/
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ù)代碼詳解的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
利用JSONObject.toJSONString()包含或排除指定的屬性
這篇文章主要介紹了利用JSONObject.toJSONString()包含或排除指定的屬性,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot中實(shí)現(xiàn)定時(shí)任務(wù)的幾種方式
定時(shí)任務(wù)在我們項(xiàng)目開發(fā)中也是很重要的,對(duì)于某些場(chǎng)景必須要用定時(shí)任務(wù)?,如定時(shí)發(fā)送郵件啊,定時(shí)統(tǒng)計(jì)數(shù)據(jù)等,這篇文章主要講講項(xiàng)目中實(shí)現(xiàn)定時(shí)任務(wù)的幾種方式,需要的朋友可以參考下2023-05-05
java中PreparedStatement和Statement詳細(xì)講解
這篇文章主要介紹了java中PreparedStatement和Statement詳細(xì)講解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Java實(shí)現(xiàn)將文件或者文件夾壓縮成zip的詳細(xì)代碼
這篇文章主要介紹了Java實(shí)現(xiàn)將文件或者文件夾壓縮成zip的詳細(xì)代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-11-11
Java實(shí)現(xiàn)短信驗(yàn)證碼和國際短信群發(fā)功能的示例
本篇文章主要介紹了Java實(shí)現(xiàn)短信驗(yàn)證碼和國際短信群發(fā)功能的示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-02-02
MyBatis?Generator快速生成實(shí)體類和映射文件的方法
這篇文章主要介紹了MyBatis?Generator快速生成實(shí)體類和映射文件的方法,通過示例代碼介紹了MyBatis?Generator?的使用,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10

