package com.itcast;
import java.util.Random;
public class ThreadScopeShareMoney {
/**
* @param args
*/
private static int money = 0;
public static void main(String[] args) {
for(int i =0;i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
money = new Random().nextInt();
System.out.println(Thread.currentThread().getName()+ " put money: " + money);
new A().get();
new B().get();
}
}).start();
}
}
static class A {
public void get() {
System.out.println("A from " + Thread.currentThread().getName()
+ " put money:" + money);
}
}
static class B {
public void get() {
System.out.println("B from " + Thread.currentThread().getName()
+ " put money: " + money);
}
}
}
运行结果:
Thread-1 put money: 1977754500
Thread-0 put money: -658790150
A from Thread-1 put money:-658790150
A from Thread-0 put money:-658790150
B from Thread-1 put money: -658790150
B from Thread-0 put money: -658790150
结果发现线程0和线程-1的A和B取出都为相同的数据,出现错误,线程不同步。
package com.itcast;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadScopeShareMoney {
/**
* @param args
*/
private static int money = 0;
private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>(); //申明Map集合
public static void main(String[] args) {
for(int i =0;i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
int money = new Random().nextInt();
System.out.println(Thread.currentThread().getName()+ " put money: " + money);
threadData.put(Thread.currentThread(), money); //把数据和当前的线程放进一个集合中,绑定线程
new A().get();
new B().get();
}
}).start();
}
}
static class A {
public void get() {
int money = threadData.get(Thread.currentThread()); //取出数据
System.out.println("A from " + Thread.currentThread().getName()
+ " put money:" + money);
}
}
static class B {
public void get() {
int money = threadData.get(Thread.currentThread()); //取出数据
System.out.println("B from " + Thread.currentThread().getName()
+ " put money: " + money);
}
}
}
结果为:
Thread-0 put money: 37664812
Thread-1 put money: -1336612286
A from Thread-0 put money:37664812
A from Thread-1 put money:-1336612286
B from Thread-1 put money: -1336612286
B from Thread-0 put money: 37664812
A和B在 线程0和线程-1取出各自钱数