Java中线程范围外共享问题

本宝宝新手,勿喷!直接上代码了,

线程范围外共享问题:各个线程之间共享同一块数据,一个多少损坏就整个毁,需要之好运作一下!

 

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);
}
}

}

相关文章