1. 程式人生 > >Java中線程範圍內共享問題

Java中線程範圍內共享問題

read current print 數據 pri sys tint new value

本寶寶新手,勿噴!直接上代碼了,

線程範圍內共享問題:各個線程之間共享同一塊數據,一個數據損壞就全部損壞,需要的可以運行一下!

public class Threads {
private static HashMap<Thread, Integer> data = 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 value = new Random().nextInt(1000);
data.put(Thread.currentThread(), value);
System.out.println("名字是:"+Thread.currentThread().getName()+"數據是:"+value);
A a1 = new A();
a1.getData();
B b1 = new B();
b1.getData();
C c = new C();
c.getDate();
}
}).start();
}
}
static class A{
public void getData(){
Thread thread = Thread.currentThread();
int value = data.get(thread);
System.out.println(thread.getName()+"從A中獲取數據"+value);
}
}
static class B{
public void getData(){
Thread thread = Thread.currentThread();
int value = data.get(thread);
System.out.println(thread.getName()+"從B中獲取數據"+value);
}
}
static class C{
public void getDate() {
Thread thread = Thread.currentThread();
int value = data.get(thread);
System.out.println(thread.getName()+"從C中獲取數據"+value);
}
}

}

Java中線程範圍內共享問題