標籤:運行 value ++ 範圍 tar private put 直接 i++
本寶寶新手,勿噴!直接上代碼了,
線程範圍內共用問題:各個線程之間共用同一塊資料,一個資料損毀就全部損壞,需要的可以運行一下!
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中線程範圍內共用問題