---恢复内容开始---
利用Map,HashMap键值对的数据结构,实现并发线程中线程范围内数据共享。
package cn.qy.heima2;import java.util.HashMap; import java.util.Map; import java.util.Random;public class ThreadScopeShareData {private static int data;private static Map<Thread,Integer> threadData=new HashMap<Thread,Integer>();public static void main(String[] args) {// TODO Auto-generated method stubfor(int i=0;i<2;i++){new Thread(new Runnable() { @Overridepublic void run() {// TODO Auto-generated method stubint 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() { synchronized (ThreadScopeShareData.class) { data=threadData.get(Thread.currentThread()); System.out.println("A from"+Thread.currentThread().getName()+"get data:"+data); } } } static class B { public synchronized void get() { synchronized (ThreadScopeShareData.class) { data=threadData.get(Thread.currentThread()); System.out.println("B from"+Thread.currentThread().getName()+"get data:"+data); } } } }
---恢复内容结束---