本宝宝新手,勿喷!直接上代码了,
线程范围内共享问题:各个线程之间共享同一块数据,一个数据损坏就全部损坏,需要的可以运行一下!
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);
}
}
}