import java.util.HashMap; import java.util.Map; import java.util.Random; public class ThreadScopeShareData { static Map<Thread, Integer> dataMap = 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 data = new Random().nextInt(100); dataMap.put(Thread.currentThread(), new Integer(data)); System.out.println("put the " + data + " into :" + Thread.currentThread()); new A().get(); new B().get(); } }).start(); } } static class A { public void get() { int data = (int) dataMap.get(Thread.currentThread()); System.out.println("A has got the data :" + data); } } static class B { public void get() { int data = (int) dataMap.get(Thread.currentThread()); System.out.println("B has got the data :" + data); } } }
更多内容请关注公众号