java多线程存钱,取钱例子

      类似javasheng生产者和消费者,同步保证数据的一致。利用wait()和notify()方法来实现线程间等待和调用。接口定义一个方法,money方法来实现接口,初始化对象,初始化金额。存钱和取钱类分别定义bank的字段。要存钱和取钱,,就要先调用接口的实现类。

TestBank2.java

package com.bank.test;

public class TestBank2 {
	public static void main(String[] args) {
		Money m =new Money(new SourceMoney(){
			public void sourceMoney(Bank a) {
				// TODO Auto-generated method stub
//				Bank b = new Bank();
				cun c =new cun(a);
				get g =new get(a);
				new Thread(c).start();
				new Thread(g).start();
			}});
		new Thread(m).start();
	}
}

money.java

package com.bank.test;

public class Money implements Runnable {
	private SourceMoney sourcemoney;
	/**
	 * @param sourcemoney
	 */
	public Money(SourceMoney sourcemoney) {
		super();
		this.sourcemoney = sourcemoney;
	}
	public void run() {
		// TODO Auto-generated method stub
		Bank b= new Bank();
		System.out.println("初始化金额");
		sourcemoney.sourceMoney(b);
	}
}
SourceMoney.java

package com.bank.test;

public interface SourceMoney {
	public void sourceMoney(Bank b);
}
get.java
package com.bank.test;

public class get implements Runnable {
	private Bank bank;

	/**
	 * @param bank
	 */
	public get(Bank bank) {
		super();
		this.bank = bank;
	}

	public void run() {
		// TODO Auto-generated method stub
		while(true){
			bank.get();
		}
		
	}
}
cun.java
package com.bank.test;

public class cun implements Runnable {
	private Bank bank;

	/**
	 * @param bank
	 */
	public cun(Bank bank) {
		super();
		this.bank = bank;
Bank.java
<pre name="code" class="java">package com.bank.test;

public class Bank {
	private int a=200;
	public synchronized void cun(){
		System.out.println("存钱前原来的钱"+a);
		if(a>=1000){
			System.out.println("停止存钱");
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		a=a+100;
		System.out.println("存钱后的金额"+a);
		this.notify();
	}
	public synchronized void get(){
		if(a<=0){
			System.out.println("不能再取钱了");
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("取钱前账户所剩的钱"+a);
		a=a-50;
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("取钱后的账户"+a);
		this.notify();
	}
}

 
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值