现在写一个Atm例子,要求每个线程输出为55,如下所示:
代码实例Main:
public class MainClass {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
Atm atm = new Atm();
public void run() {
atm.save();
}
};
for(int i = 0; i < 10; i++) {
new Thread(runnable).start();
}
}
}
代码实例Atm:
public class Atm{
private int money;
public void save() {
for(int i = 1; i <= 10; i++) {
money+= i;
}
System.out.println(Thread.currentThread().getName() + "-" + money);
}
}
执行结果:
Thread-0-55
Thread-3-275
Thread-4-220
Thread-1-110
Thread-2-165
Thread-7-330
Thread-8-440
Thread-6-440
Thread-9-495
Thread-5-550
因为Atm对象多线程共享,线程不同步,导致输出结果错误。