package desposit.money;
public class DespositMoney {
public static void main(String[] args) {
Customer c1 = new Customer("第一个顾客",3);
Customer c2 = new Customer("第二个顾客",10);
Customer c3 = new Customer("第三个顾客",5);
c1.start();
c2.start();
c3.start();
}
}
class Customer extends Thread{
private int time;
String s;
public Customer(String s,int time){
this.s = s;
this.time = time;
}
public void run(){
while(true)
{
synchronized(this){
if(time>0)
{
Total.sum+=100;
System.out.println(s+"存款100元,银行总共有存款"+Total.sum+"元");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
time --;
}
if(time ==0)
{
System.out.println(s+"存款结束");
break;
}
}
}
}
}
class Total {
public static int sum = 0;
}
运行结果不是从100,200,……,到1800,中间总有重复的数字,但最后的结果总和是1800
多个线程访问同一个对象时,加synchronized(this)可以让一个时间内只有一个线程处理,但是你这里new了3个对象。
我感觉要怀疑的你的eclipse了,我完全复制的代码,重新运行了一遍,结果是这样的:
没有重复的数字,按照顺序依次存钱啊,结果也是正确的

这篇博客通过Java实现了一个多线程模拟存款的过程,创建了Customer类继承自Thread,每个Customer代表一个线程,同步方法`synchronized(this)`确保同一时间只有一个线程执行存款操作。在测试中,虽然出现了重复的存款数字,但最终总和正确,问题可能出在Eclipse上。重新运行代码后,结果显示无重复,顺序存款,结果正确。
680

被折叠的 条评论
为什么被折叠?



