<span style="font-size:24px;">import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/*
* 线程范围内共享变量的概念与作用,创建三个线程,都访问了三个对象
* 第一个对象设置值,第二第三个对象取值,同一个线程设置的值,只能被相同的线程获取
*/
public class ThreadScopeShareDate {
private static int data = 0;
private static Map<Thread, Integer> threadData = 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().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()
+ "has put data" + data);
}
}
static class B {
public void get() {
int data = threadData.get(Thread.currentThread());
System.out.println("B from" + Thread.currentThread().getName()
+ "has put data" + data);
}
}
}
</span>
多线程中范围内共享变量的概念与作用
最新推荐文章于 2022-01-22 14:04:04 发布