初次尝试
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);
}
}
}
发现取得的数据不正确
修改代码,再次尝试
public class ThreadScopeShareData {
private static int data = 0;
private static Map<Thread,Integer> threadDate = 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() {
data = new Random().nextInt();
System.out.println(Thread.currentThread().getName() + "has put data :" + data);
threadDate.put(Thread.currentThread(),data);
new A().get();
new B().get();
}
}).start();
}
}
static class A{
public void get(){
int data =threadDate.get(Thread.currentThread());
System.out.println("A from " + Thread.currentThread().getName() + " get data :" + data);
}
}
static class B{
public void get(){
int data =threadDate.get(Thread.currentThread());
System.out.println("B from " + Thread.currentThread().getName() + " get data :" + data);
}
}
}
数据获取正确
也可以使用ThreadLocal来实现
public class ThreadLocalTest {
private static ThreadLocal<Integer> x = new ThreadLocal<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);
x.set(data);
new A().get();
new B().get();
}
}).start();
}
}
static class A{
public void get(){
int data =x.get();
System.out.println("A from " + Thread.currentThread().getName() + " get data :" + data);
}
}
static class B{
public void get(){
int data =x.get();
System.out.println("B from " + Thread.currentThread().getName() + " get data :" + data);
}
}
}
效果相同