package cn.hinge.yangjun;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadScopeShareData {
/**
* 线程范围内共享数据:此demo分2种情况,
1.除去红色部分代码,运行demo1.会看见 线程之间共享的数据并不独立
* 2.加上红色部分代码,实现各自线程数据共享独立请看如下实例:
那么线程范围内的共享变量有什么用呢?银行转帐就是一个很好的实例。
*/
private static int data = 0; //全局成员变量
private static Map map = new HashMap();
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().getName()
+ " has put date:" + data);
map.put(Thread.currentThread(), data);
//A 获取数据
new A().get();
//B 获取数据
new B().get();
}
}).start();
}
}
/* A 模块 */
static class A {
public void get() {
int data = map.get(Thread.currentThread());
System.out.println("A from " + Thread.currentThread().getName()
+ " get data:" + data);
}
}
/* B 模块 */
static class B {
public void get() {
int data = map.get(Thread.currentThread());
System.out.println(" B from " + Thread.currentThread().getName()
+ " get data:" + data);
}
}
}
运行结果:
Thread-1 has put date:1897609462
Thread-0 has put date:-1924516760
A from Thread-0 get data:-1924516760
B from Thread-0 get data:-1924516760
A from Thread-1 get data:1897609462
B from Thread-1 get data:1897609462
可见 线程Thread-0获取数据一致,而线程Thread-1也是一直 ,2个线程共享的数据是对立的。
阅读(1515) | 评论(0) | 转发(0) |