1. 程式人生 > >java 之 執行緒間變數共享

java 之 執行緒間變數共享

import java.util.Random;

public class StaticTest {
	
	private static int data = 0;

	public static void main(String[] args) {
		//開三個執行緒
				for(int i=0;i<3;i++) {
					new Thread(new Runnable() {

						@Override
						public void run() {
							//每個執行緒data值都一樣,下邊的程式有解釋
						 data = new Random().nextInt();
							System.out.println(Thread.currentThread().getName() + " has put data :"+ data);
						}
						
					}).start();
				}
	}

}

執行結果:

Thread-1 has put data :367396051
Thread-2 has put data :367396051
Thread-0 has put data :367396051

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


public class ThreadScopeShareData {

	//靜態,會造成一樣的隨機值,此處有點不理解
	private static int data = 0;
	//以執行緒作為key
	private static Map<Thread,Integer> threadData = new HashMap<Thread, Integer>();
	
	public static void main(String[] args) {
		//開三個執行緒
		for(int i=0;i<3;i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					//每個執行緒data值都一樣,因為是靜態變數,一改全改,最後的結果跟最後的執行緒data值一樣
					//被後來的執行緒data值覆蓋了,因為靜態變數只有一份
//					data = new Random().nextInt();
					//這樣就不同了
					int data = new Random().nextInt();
					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() {
			int data = threadData.get(Thread.currentThread());
			System.out.println("A from  "+Thread.currentThread().getName()+" get data : " +data);
		}
	}
	
	static class B {
		public void get() {
			int data = threadData.get(Thread.currentThread());
			System.out.println("B from  "+Thread.currentThread().getName()+" get data : " +data);
		}
	}
}


map模擬了ThreadLocal。

執行結果:

Thread-0 has put data :1500573848
Thread-2 has put data :1307429900
Thread-1 has put data :-1173968999
A from  Thread-1 get data : -1173968999
A from  Thread-0 get data : 1500573848
A from  Thread-2 get data : 1307429900
B from  Thread-1 get data : -1173968999
B from  Thread-0 get data : 1500573848
B from  Thread-2 get data : 1307429900