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); } } }
更多内容请关注公众号
JAVA线程间共享变量
时间: 2024-09-30 16:39:34