- 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();
-
-
- }
- }
posted @
2014-11-26 11:35
流寂
阅读(
1314)
评论()
编辑
收藏
举报