线程范围内的共享变量

2014-11-24 10:33:39 · 作者: · 浏览: 0

[java]
package cn.itcast.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ThreadScopeShareData {
/*
* 线程范围内的共享变量
* 作用:线程范围内的共享变量是指对同一个变量,几个线程同时对它进行写和读操作,
* 而同一个线程读到的数据就是它自己写进去的数据。
*/
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(){

public void run() {
data = new Random().nextInt();
map.put(Thread.currentThread(), data);

System.out.println(Thread.currentThread().getName() + ":MAIN--->" + map.get(Thread.currentThread()));
new A().get();
new B().get();
}
}).start();
}
}

static class A{
public void get()
{
System.out.println(Thread.currentThread().getName()+ "--->" + map.get(Thread.currentThread()));
}
}
static class B{
public void get()
{
System.out.println(Thread.currentThread().getName()+ "--->" +map.get(Thread.currentThread()));
}
}

}