Acount.java
Acount类,包括存钱,取钱的方法
package com.Thread;
class Acount{
private String no;//ID
private double count;//银行卡余额
private boolean flag = false;
public Acount(String no,double count){
this.no = no;
this.count = count;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public double getCount() {
return count;
}
public void setCount(double count) {
this.count = count;
}
//同步方法,属于对象,所以此处的监视锁相当于this
public synchronized void draw(double drawAcount){
if(flag){
if(drawAcount <= this.getCount()){
//System.out.println("取钱成功,吐出钞票"+drawAcount);
//修改余额
this.setCount(this.getCount()-drawAcount);
System.out.println("取钱成功,余额为:"+this.getCount());
flag = false;
//取钱结束后,唤醒wait()的线程
this.notifyAll();
}
else{
System.out.println("余额不足,取钱失败");
}
}else{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//同步方法,属于对象,所以此处的监视锁相当于this
public synchronized void dispos(double disposAcount){
//修改余额
if(!flag){
this.setCount(this.getCount()+disposAcount);
System.out.println("存钱成功,余额为:"+this.getCount());
flag = true;
//存钱结束后,唤醒wait()的线程
this.notifyAll();
}
else{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
disposThread.java
存钱线程
//存钱线程
package com.Thread;
public class disposeThread extends Thread {
private Acount acount;
private double disposAcount;
public disposeThread(Acount acount,double disposAcount){
this.acount = acount;
this.disposAcount = disposAcount;
}
public void run() {
//System.out.println("存钱线程:");
for(int i = 0; i< 10;++i){
System.out.println("存钱线程:"+i);
acount.dispos(disposAcount);
}
}
}
DrawThread2.java
取钱线程,主函数
package com.Thread;
//使用Acount类
public class DrawThread2 extends Thread {
private Acount acount;
private double drawAcount;
public DrawThread2(Acount acount,double drawAcount){
this.acount = acount;
this.drawAcount = drawAcount;
}
public void run() {
// System.out.println("取钱线程:");
for(int i = 0;i<10;i++){
System.out.println("取钱线程:"+i);
acount.draw(drawAcount);
}
}
public static void main(String[] args) {
Acount acount = new Acount("lily",1000.0);
//启动两个并发的线程对acount取钱
//new DrawThread(acount,1000.0).start();
//new DrawThread(acount,1000.0).start();
new disposeThread(acount,1000.0).start();
new DrawThread2(acount,1000.0).start();
}
}
其中一次的执行结果
存钱线程:0
取钱线程:0
存钱成功,余额为:2000.0
存钱线程:1
取钱成功,余额为:1000.0
取钱线程:1
存钱线程:2
存钱成功,余额为:2000.0
存钱线程:3
取钱线程:2
取钱成功,余额为:1000.0
取钱线程:3
存钱线程:4
存钱成功,余额为:2000.0
存钱线程:5
取钱线程:4
取钱成功,余额为:1000.0
取钱线程:5
存钱线程:6
存钱成功,余额为:2000.0
存钱线程:7
取钱线程:6
取钱成功,余额为:1000.0
取钱线程:7
存钱线程:8
存钱成功,余额为:2000.0
存钱线程:9
取钱线程:8
取钱成功,余额为:1000.0
取钱线程:9