我写了一个有关线程的类同步线程我想假设有3个人去银行取钱银行里面只有100块了第一个人存了5000块 第二人要取6000块可是钱不够啊我想叫他等银行有6000块的时候在叫他来取钱,第三个人是来存钱的存了4000然后经过上诉处理银行里面应该只有100+5000+4000-6000的钱了我就想实现的这个功能可是写了半天都写不出来麻烦各位哥哥帮帮我一下!下面是我写的代码能够在我的代码上面修改最好谢谢了!
package com.text;
public class TestThread {
public static void main(String[] args) {
User user = new User("yonghu", 100);
BankMessage tt1 = new BankMessage(user, "tt1", 5000);
BankMessage tt2 = new BankMessage(user, "tt2", 6000);
BankMessage tt3 = new BankMessage(user, "tt3", 4000);
Thread t1 = new Thread(tt1);
Thread t2 = new Thread(tt2);
Thread t3 = new Thread(tt3);
t1.start();
t2.start();
t3.start();
}
}
package com.text;
public class BankMessage implements Runnable {
private User user;
private String name;
private float y;//用户要取的钱
public BankMessage(User user, String name, float y) {
super();
this.user = user;
this.name = name;
this.y = y;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void run() {
user.setName(name);
if (y > 0) {
user.setStoremoney(y);
}
if (y < 0) {
user.setGetmoney(y);
}
user.MoneyMession();
}
}
package com.text;
public class User {
private String name;
private float money;// 里面盛德钱
private float storemoney;// 存钱
private float getmoney;// 取钱
public User() {
super();
}
public User(String name, float money) {
super();
this.name = name;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
public float getStoremoney() {
return storemoney;
}
public void setStoremoney(float storemoney) {
this.storemoney = storemoney;
}
public float getGetmoney() {
return getmoney;
}
public void setGetmoney(float getmoney) {
this.getmoney = getmoney;
}
public synchronized float MoneyMession() {
System.out.println("你要存的钱:" + storemoney);
System.out.println("你要取的钱:" + getmoney);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (money + getmoney < 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (getmoney < 0 && money + getmoney > 0) {
money += getmoney;
System.out.println(name+"你取的钱为"+getmoney);
} else {
money += storemoney;
System.out.println(name+"你存的钱为"+storemoney);
}
if (money + getmoney < 0 && Float.toString(getmoney).equals("0.0")) {
notify();
}
System.out.println(money);
return money;
}
}