欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA多线程的一个复习例子(取款同步)(希望大家不要看源代码,看题目自己写出实现)

程序员文章站 2022-07-14 20:10:25
...
    目的:练习JAVA多线程锁的机制。
     题目要求:假设某银行服务器内存储了1000块钱的数据信息,现有两台ATM同时取款,一个取800,一个取700,用多线程解决同时取款的问题

























这里贴出我写的源代码(其实是网上资料,自己复习用)
   
        /**
 * 银行账户类
 * @author 刘峰
 *
 */
public class Account {
	
	private float balance = 1000;

	public float getBalance() {
		return balance;
	}

	public void setBalance(float balance) {
		this.balance = balance;
	}
	
	/**
	 * 取款(同步)
	 * @param money
	 * author by 刘峰
	 * 2010-6-21下午04:43:45
	 */
	public synchronized void withdraw(float money){
		if(balance >= money){
			System.out.println("被取走"+money+"元");
			
			try{
				Thread.sleep(1000);

			}catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }

			//扣钱
			balance -= money;
		}else{
			System.out.println("对不起,余额不足!");
		}
		
	}
}
 


/**
 * ATM1
 * @author 刘峰
 *
 */
public class TestAccount1 extends Thread {
	private Account account;

	public TestAccount1(Account account){
		this.account = account;
	}
	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}
	
	public void run(){
		System.out.println(this.getName() + "来取"+800+"块钱");
		account.withdraw(800);
		System.out.println("余额为:" + account.getBalance() + "元!");
	}
	
	
}


    /**
 * ATM2
 * @author 刘峰
 *
 */
public class TestAccount2 extends Thread {
	
	private Account account;

	public TestAccount2(Account account){
		this.account = account;
	}
	
	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}
	
	public void run(){
		System.out.println(this.getName() + "来取"+700+"块钱");
		account.withdraw(700);
		System.out.println("余额为:" + account.getBalance() + "元!");
	}
	

}




测试:
public class Test {

	/**
	 * @param args
	 * author by 刘峰
	 * 2010-6-21下午04:55:11
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Account account = new Account();
		TestAccount1 acc1 = new TestAccount1(account);
		TestAccount2 acc2 = new TestAccount2(account);
		acc1.start();
		acc2.start();
	}

}




输出到控制台的信息:

    Thread-0来取800块钱
    Thread-1来取700块钱
    被取走700.0元
    对不起,余额不足!
    余额为:300.0元!
    余额为:300.0元!

如果大家觉得两个线程不够用的话,可在上面代码优化,方便理解JAVA线程