package net.okren.java;
import java.io.*;
//账户
class Account{
private float balance = 1000;
public float getBalance(){
return balance;
}
public void setBalance(float balance){
this.balance = balance;
}
public synchronized void withDraw(float money){
if(balance >= money){
System.out.println("取走 "+ money +"钱");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
balance -= money;
}else{
System.out.println("余额不足 ");
}
}
}
class TestAccount1 extends Thread{
private Account account;
public TestAccount1(Account account){
this.account = account;
}
public void run(){
account.withDraw(800);
System.out.println("余额为"+ account.getBalance());
}
}
class TestAccount2 extends Thread{
private Account account;
public TestAccount2(Account account){
this.account = account;
}
public void run(){
account.withDraw(700);
System.out.println("余额为 " + account.getBalance());
}
}
public class JavaTest {
public static void main(String[] args){
Account account = new Account();
TestAccount1 t1 = new TestAccount1(account);
TestAccount2 t2 = new TestAccount2(account);
t1.start();
t2.start();
}
}
java多线程 银行取款
最新推荐文章于 2022-07-09 10:41:48 发布