现在的位置: 首页 > 综合 > 正文

java线程系列—线程范围内共享变量(一)

2018年04月12日 ⁄ 综合 ⁄ 共 843字 ⁄ 字号 评论关闭

在java开发中,有时会遇到这种情况,有一变量,其中有三个模块去访问,在多个线程中,确保,在同一线程内,其访问的是同一变量,这时就要实现线程范围内共享变量

源代码如下:

public class ThreadSharaDate {

private static Map<Thread,Integer> map = new HashMap<Thread,Integer>();
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("this is "+Thread.currentThread().getName()+"---"+data);
map.put(Thread.currentThread(), data);
new A().getDate();
new B().getDate();
}
}).start();
}

}


static class A{
public void getDate(){
int date = map.get(Thread.currentThread());
System.out.println("A thread is "+Thread.currentThread().getName()+"--" +date);
}
}

static class B{
public void getDate(){
int date = map.get(Thread.currentThread());
System.out.println("B thread is"+Thread.currentThread().getName()+"--" +date);
}
}

}

关于线程范围内共享变量,有两种方法,一种是通过HashMap来标志是同一线程时,取同一变量,另一种方法,可以调用ThreadLocal来实现,具体代码,请看下一篇文章。

抱歉!评论已关闭.