package _7_26;
import java.util.Random;
public class ThreadScopeShareData2 {
private static int data = 0;
// private static Map<Thread, Integer> threadData = 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() {
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();
}
new Thread(new Runnable(){
@Override
public void run() {
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);
}
}
}
for循环里的两个线程为什么生成的随机数都一样??
在for循环外面新建一个线程,却能生成不同的随机数?谁给解释一下,这个很蹊跷。
---------------运行结果:------------------
Thread-0 has put data :1500315473
Thread-1 has put data :1500315473
Thread-2 has put data :445127673
A from Thread-0 get data :445127673
A from Thread-2 get data :445127673
A from Thread-1 get data :445127673
B from Thread-1 get data :445127673
B from Thread-2 get data :445127673
B from Thread-0 get data :445127673
------------------------------------------------
就看前三行,前两个线程产生的随机数和后一个不同,为什么啊?按理说应该是三个都不同才对,前两个相同,还能是因为for循环里的两个线程顺便就把变量共享了么?? |