一个线程调用A,B,C三个模块,模块中的表达式或变量调用访问一个数据,这个数据可以是静态的。
另一个线程也调用A,B,C三个模块,模块中的表达式或变量访问的数据,就不是刚才的数据,而是另一个同样的代码,一个线程身上一分数据
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadScopeShareData {
?private static int data = 0;
?private static Map threadData = 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(Thread.currentThread().getName()+
? ? ? " has put data: "+data);
? ? threadData.put(Thread.currentThread(),data);
? ? new A().get();
? ? new B().get();
? ? }
? }).start();
? }
?}
?static class A{
? public void get(){
? int data = threadData.get(Thread.currentThread());
? System.out.println("A from "+Thread.currentThread().getName()+
? ? " get data: "+data);
? }
?
?}
?static class B{
? public void get(){
? int data = threadData.get(Thread.currentThread());
? System.out.println("B from "+Thread.currentThread().getName()+
? ? " get data: "+data);
? }
?}
}
应用场景:数据库,一个方法是输入数据,一个方法是输出数据,两个独立的对象,
A在向B输入数据,B在向外输出数据,A->B->
C在向D输入数据,D在向外输出数据,C->D->
两条线共用同一个链接对象,如果C这条线路结束了,提交结果,那么不就把A所在的线程中断了么,所以每一条线程上操作的都是自己的数据,线程操作的数据,是自己线程范围内的数据,与另外线程上的数据无关(银行转账也是如此)
以上实例演示了,线程范围内,(不同模块)数据共享,线程范围外,数据独立

?