java-线程-线程内共享变量的实现
2011-10-06 11:00
495 查看
public class ThreadScopeShareData { /** * @param args */ private static HashMap<Thread, Integer> map = 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(); System.out.println(Thread.currentThread() +" data is "+data); map.put(Thread.currentThread(), data); new A().get(); new B().get(); } }).start(); } } static class A{ public void get(){ int data = map.get(Thread.currentThread()); System.out.println("A get data:" + data + " from " + Thread.currentThread().getName()); } } static class B{ public void get(){ int data = map.get(Thread.currentThread()); System.out.println("B get data:" + data + " from " + Thread.currentThread().getName()); } } }
运行结果如下
看到结果,很容易可以知道线程内共享变量的定义就是:同一个线程内该变量一样,不同线程间变量值不一样。
这里主要用了一个hashmap来实现了上述的功能,代码比较简单,不再详述
最后:今天是乔帮主走的日子
相关文章推荐
- 五:java中线程范围内共享变量--Map实现
- Java线程总结(四):ThreadLocal实现线程范围的共享变量
- java基础--线程03--实现线程范围内的共享变量
- Java版:多线程共享变量方式及实现
- ThreadLocal实现线程范围的共享变量
- 多线程篇四:ThreadLocal实现线程范围内变量共享
- java多线程:线程范围内共享变量(四)
- java线:辛格尔顿隐藏ThreadLocal实现线程数据共享
- 【线程高新】——【ThreadLocal实现线程范围的共享变量】
- ThreadLocal实现线程范围的共享变量
- ThreadLocal实现线程范围的共享变量
- Java线程重复执行以及操作共享变量的代码示例
- java并发-多线程之线程范围内共享变量(5)
- 4.ThreadLocal实现线程范围的共享变量
- ThreadLocal为共享资源创建线程本地副本变量实现线程安全
- java 使用volatile实现线程数据的共享
- ThreadLocal实现线程范围的共享变量-笔记整理4
- 使用JDK提供的ThreadLocal实现线程范围的共享变量(类似于Map<Thread,Variable>)
- 六:java中线程范围内共享变量--ThreadLocal
- JAVA 并发编程-线程范围内共享变量(五)