线程范围共享数据图解:
代码演示:
package tradition;
import java.util.Random;
/**
* 线程区域内的共享数据
*/
public class ThreadScopeShareData {
private static int data = 0;
public static void main(String[] args) {
for(int i = 0; i < 2; i ++) {
//创建一个线程
new Thread(new Runnable(){
@Override
public void run() {
data = new Random().nextInt();
System.out.println(Thread.currentThread()
.getName() + " has put data : " + data);
new A().get();
new B().get();
}
}).start();
}
}
static class A{
public void get() {
System.out.println("A from " + Thread.currentThread()
.getName() + " get data :" + data);
}
}
static class B{
public void get() {
System.out.println("B from " + Thread.currentThread()
.getName() + " get data :" + data);
}
}
}
控制台打印的结果:
数据不一致,A和B从线程0中的拿到的数据应该是1935101964。也就是说不通的两个线程访问的是同一份数据,但是不通的线程访问的数据应该是相互独立的。
解决该问题后的代码:package tradition;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* 线程区域内的共享数据
*/
public class ThreadScopeShareData {
//创建一个HashMap
private static Map<Thread, Integer> threadData = 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 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);
}
}
}
控制台打印的结果:
上面打印的结果正常。