import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by lwc on 4/22/16.
*/
public class ThreadSharaDate {
private static Map<Thread,Integer> map = new HashMap<>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
public void run(){
int data = new Random().nextInt();
System.out.println("this is "+Thread.currentThread().getName()+"---"+data);
map.put(Thread.currentThread(), data);
new A().getDate();
new B().getDate();
}
}).start();
}
}
static class A{
public void getDate(){
int date = map.get(Thread.currentThread());
System.out.println("A thread is "+Thread.currentThread().getName()+"--" +date);
}
}
static class B{
public void getDate(){
int date = map.get(Thread.currentThread());
System.out.println("B thread is"+Thread.currentThread().getName()+"--" +date);
}
}
}
实现ThreadLocal功能
最新推荐文章于 2024-08-26 17:07:51 发布
本文通过一个Java示例展示了如何在多个线程中共享数据,并通过子类A和B来获取当前线程的数据。该示例使用了HashMap来保存每个线程的数据,通过随机数生成线程特有数据,最后由A类和B类的方法输出这些数据。

1587

被折叠的 条评论
为什么被折叠?



