📄 bank.java
字号:
class Bank implements Runnable
{
int money=300;
int time1,time2,time3,time4;
Thread accountant1,accountant2,cashier1,cashier2;
public Bank()
{
accountant1=new Thread(this);
accountant1.setName("会计");
accountant2=new Thread(this);
accountant2.setName("会计");
cashier1=new Thread(this);
cashier2=new Thread(this);
cashier1.setName("出纳");
cashier2.setName("出纳");
}
public void run()
{
for(int i=1;i<=3;i++)
{
if(Thread.currentThread()==accountant1)
{
time1=i;
saveOrtake(30);
}
else if(Thread.currentThread()==cashier1)
{
time2=i;
saveOrtake(30);
}
}
for(int i=4;i<=6;i++)
{
if(Thread.currentThread()==accountant2)
{
time3=i;
saveOrtake(45);
}
else if(Thread.currentThread()==cashier2)
{
time4=i;
saveOrtake(45);
}}
}
public synchronized void saveOrtake(int number)
{int i=1;
if(Thread.currentThread()==accountant1)
{
System.out.printf("%s%d\n","今天是星期",time1);
while(i<=3)
{i++;
money=money+number;
try {
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
System.out.printf("%s,目前帐户上有%d万元\n","我是"+accountant1.getName(),money);
}
}
else if(Thread.currentThread()==cashier1)
{
System.out.printf("%20s%d\n","今天是星期",time2);
while(i<=2)
{i++;
money=money-number/2;
try{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
System.out.printf("%20s,目前账上有%d万元\n","我是"+cashier1.getName(),money);
}
}
else if(Thread.currentThread()==accountant2)
{
while(i<=4)
{ i++;
try {
wait();
money=money+number;
System.out.printf("%40s%d\n","今天是星期",time3);
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
System.out.printf("%40s,目前帐户上有%d万元\n","我是"+accountant2.getName(),money);
}
}
else if(Thread.currentThread()==cashier2)
{
while(i<=4)
{ i++;
try{wait();
money=money-number/3;System.out.printf("%60s%d\n","今天是星期",time4);
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
System.out.printf("%60s,目前账上有%d万元\n","我是"+cashier2.getName(),money);
}
}
notifyAll();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -