java多线程模拟多用户_java模拟多用户取款(多线程同步)

package com.multiThreadstudy;

public class Bank {

protected final static int MUN_ACCOUNTS=8;

private int[] accounts=new int[MUN_ACCOUNTS];

public Bank()

{

for(int i=0;i

{

accounts[i]=10000;

}

}

public void showAccounts()

{

int total=0;

for(int i=0;i

{

total+=accounts[i];//System.out.println(i);

}

System.out.println("银行总存款为"+total);

}

public synchronized void transfer(int from,int into,int amount)

{

if(accounts[from]>=amount&&from!=into)

{

int newAccountFrom=accounts[from]-amount;

int newAccountInto=accounts[into]+amount;

try {

Thread.sleep(3000);

accounts[from]=newAccountFrom;

accounts[into]=newAccountInto;

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

public int getAmount(int id)

{

return accounts[id];

}

}

package com.multiThreadstudy;

public class Customer extends Thread {

private int customerID;

private boolean running;

private Bank bank;

public Customer(int id,Bank bank)

{

this.customerID=id;

this.running=false;

this.bank=bank;

}

public void run()

{

int into=0;

int amount=0;

while(running)

{

into=(int)(Bank.MUN_ACCOUNTS*Math.random());

amount=(int)(bank.getAmount(this.customerID)*Math.random());

bank.transfer(this.customerID,into,amount);

yield();//让其他线程有运行的时间

}

}

public void start()

{

running=true;

super.start();

}

public void halt()

{

running=false;

}

}

package com.multiThreadstudy;

public class test {

public static void main(String[] args)

{

Bank bank=new Bank();

Customer[] customers=new Customer[Bank.MUN_ACCOUNTS];

for(int i=0;i

{

customers[i]=new Customer(i,bank);

customers[i].start();

}

for(int i=0;i<40;i++)

{

bank.showAccounts();

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

} 如果没有在transfer函数加上

synchronized,哪门银行的总存款会不断的减少。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值