首页 > 代码库 > java多线程 银行取款
java多线程 银行取款
- 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多线程 银行取款
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。