Demo entry 6687674

1

   

Submitted by 1 on Dec 30, 2017 at 07:21
Language: Java. Code size: 2.6 kB.

package 线程;
/*
 * 存一次钱取一次钱  一个线程存钱 多个线程取钱
 */
public class XianChengTongXin {
	public static void main(String[] args) {
		Account acc = new Account("1234567", 0);
		Runnable draw = new DrawThread(acc,800);
		Runnable deposit = new DepositThread(acc,800);
		new Thread(draw).start();
		new Thread(draw).start();
		new Thread(draw).start();
		new Thread(deposit).start();
	}
}
class Account{
	private String accountNo;
	private double balance;
	//模拟账户
	private boolean flage = false;
	
	public Account() {
		super();		
	}
	public Account(String accountNo, double balanc) {
		super();
		this.accountNo = accountNo;
		this.balance = balanc;
	}
	public String getAccountNo() {
		return accountNo;
	}
	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}
	public double getBalanc() {
		return balance;
	}
	public synchronized void draw(double drawAmount){//取钱操作
		try {
			if(!flage){
				wait();//如果flage为false表示账户里没有存款或者存款小于取款数 则取钱线程等待 
			}else{
				//flage为true账户里面有存款,取钱线程进行取钱操作
				balance -= drawAmount;
				System.out.println(Thread.currentThread().getName()+"取钱成功 !  取钱金额"+drawAmount+"------账户余额:"+balance);
				flage = false;//存款已经被取完 将标识符更改 表示账户已经没钱
				notifyAll();//将被暂时等待的存钱线程唤醒
			}
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
	}
	public synchronized void deposit(double depositAmount){
		try {
			if(flage){//如果flage为true 存钱线程等待
				wait();
			}else{
				//flage为false 账户已经没钱 需要存钱线程执行存钱钱操作做
				balance += depositAmount;
				System.out.println(Thread.currentThread().getName()+"存钱成功  余额为"+balance);
				flage = true;
				notifyAll();
				}
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		//存钱
	}
}

class DrawThread implements Runnable{
	private Account account;
	private double drawAmount;//打算取钱的数目
	
	public DrawThread(Account account, double drawAmount) {
		super();
		this.account = account;
		this.drawAmount = drawAmount;
	}

	@Override
	public void run() {
		for(int i = 0 ; i <= 100 ; i++){
			account.draw(drawAmount);
		}
	}
	
}

class DepositThread implements Runnable{
	private Account account;//传入账户类 进行存钱操作
	private double depositAmount;//打算存钱的数目
	
	public DepositThread(Account account, double depositAmount) {
		super();
		this.account = account;
		this.depositAmount = depositAmount;
	}

	@Override
	public void run() {
		
		for(int i = 0 ; i <= 100 ; i++){
			account.deposit(depositAmount);
		}
	}
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).