package com.wsy.model; import java.util.HashMap; import java.util.Map; import java.util.Random; public class ThreadScopeShareData { private static Map<Thread, Integer> threadDataMap = new HashMap<Thread, Integer>(); public static void main(String[] args) { final A a = new A(); final B b = new B(); for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { int data = new Random().nextInt(); System.out.println(Thread.currentThread() + " data is " + data); threadDataMap.put(Thread.currentThread(), data); a.getData(); b.getData(); } }).start(); } } static class A { public void getData() { System.out.println("A: data is " + threadDataMap.get(Thread.currentThread()) + " of " + Thread.currentThread().getName()); } } static class B { public void getData() { System.out.println("B: data is " + threadDataMap.get(Thread.currentThread()) + " of " + Thread.currentThread().getName()); } } }
输出结果:
Thread[Thread-0,5,main] data is 160847734
Thread[Thread-1,5,main] data is 1298550232
A: data is 1298550232 of Thread-1
A: data is 160847734 of Thread-0
B: data is 160847734 of Thread-0
B: data is 1298550232 of Thread-1