简单写了一下,包括程序入口一共5个类:
/**
*程序入口
*/
public class Test {
public static void main(String[] args) {
new Father().start();
new Mother().start();
new Son().start();
}
}public abstract class Family extends Thread {
Random r = new Random();
/**
* 等待时间
*/
public static final int SLEEP_LIMIT = 1000;
protected String name;
public Family() {
this.setName();
}
protected abstract void setName();
// 总资产
private static int money;
protected synchronized boolean updateMoney(int addOrReduce) {
if (money + addOrReduce < 0) {
System.out.println(addOrReduce + "钱不够了." + name + " 等待.");
return false;
}
money += addOrReduce;
printInfo(name, addOrReduce);
return true;
}
private static void printInfo(String name, int num) {
StringBuilder sb = new StringBuilder();
sb.append(name + " ");
if (num > 0) {
sb.append(" 挣了 " + num + " 元.当前总余额: " + money);
sb.append("\n~~~~~~~~~~~~~~~~~~~~~~~~~");
} else {
sb.append(" 花了 " + (-num) + " 元.当前总余额: " + money);
}
System.out.println(sb.toString());
}
}public class Father extends Family {
@Override
public void run() {
while (true) {
try {
Thread.sleep(Family.SLEEP_LIMIT);
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
super.updateMoney(100);
}
}
@Override
protected void setName() {
this.name = "father";
}
}public class Mother extends Family {
@Override
public void run() {
while (true) {
try {
Thread.sleep(Family.SLEEP_LIMIT);
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
int num = r.nextInt(80);
super.updateMoney(0 - num);
}
}
@Override
protected void setName() {
this.name = "mother";
}
}
public class Son extends Family {
@Override
public void run() {
while (true) {
try {
Thread.sleep(Family.SLEEP_LIMIT);
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
int num = r.nextInt(30);
super.updateMoney(0 - num);
}
}
@Override
protected void setName() {
this.name = "son";
}
}