1. 程式人生 > >多執行緒與併發----執行緒範圍內共享變數

多執行緒與併發----執行緒範圍內共享變數

執行緒範圍內共享資料圖解:

mport java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ThreadScopeShareDate {

	//三個模組共享資料,主執行緒模組和AB模組
	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() {
				
				@Override
				public void run() {
					//現在當前執行緒中修改一下資料,給出修改資訊
					int data=new Random().nextInt();
					//Thread.currentThread()獲取當前執行緒。
					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(){ data=threadData.get(Thread.currentThread()); System.out.println("A from"+Thread.currentThread().getName()+" get data:"+data); } } static class B{ public void get(){ data=threadData.get(Thread.currentThread());
System.out.println("B from"+Thread.currentThread().getName()+" get data:"+data); } } }

執行結果為:

Thread-0 has put data:836161760
Thread-1 has put data:-570080145
A fromThread-1 get data:-570080145
A fromThread-0 get data:-570080145
B fromThread-1 get data:836161760
B fromThread-0 get data:836161760

結果並沒與實現執行緒間的資料同步,兩個執行緒使用的是同一個執行緒的資料。要解決這個問題,可以將每個執行緒用到的資料與對應的執行緒號存放到一個

map集合中,使用資料時從這個集合中根據執行緒號獲取對應執行緒的資料。程式碼實現:上面紅色部分

程式中存在的問題:獲取的資料與設定的資料不同步

Thread-1共享資料設定為:-997057737

            Thread-1--A 模組資料:-997057737

            Thread-0共享資料設定為:11858818

            Thread-0--A 模組資料:11858818

            Thread-0--B 模組資料:-997057737

            Thread-1--B 模組資料:-997057737

最好將Runnable中設定資料的方法也寫在對應的模組中,與獲取資料模組互斥,以保證資料同步