类似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();
}
}