您的位置:首页 > 编程语言 > Java开发

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来实现了上述的功能,代码比较简单,不再详述

最后:今天是乔帮主走的日子
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: