package Thread;
public class Test1 {
public static void main(String[] args) {
ShareBank account = new ShareBank();
Husband husband = new Husband(account, 100); // 假设丈夫每天收入100元
Wife wife = new Wife(account, 50, 200); // 假设妻子每次消费在50元到200元之间
husband.start();
wife.start();
}
}
package Thread;
public class ShareBank {
private double balance;//共享账户
// 存款方法
public synchronized void deposit(int amount) {
balance += amount;
System.out.println("存款成功,当前余额:" + balance);
}
// 取款方法
public synchronized void withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("取款成功,当前余额:" + balance);
} else {
}
}
}
package Thread;
import java.util.Random;
public class Husband extends Thread {
private ShareBank account;
private int income;
Random r=new Random();
public Husband(ShareBank account, int income) {
this.account = account;
this.income = income;
}
@Override
public void run() {
while (true) {
account.deposit(income);
try {
Thread.sleep(r.nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package Thread;
import java.util.Random;
public class Wife extends Thread{
private ShareBank account;
private int min;
private int max;
Random r=new Random();
public Wife(ShareBank account, int min, int max) {
this.account = account;
this.min = min;
this.max = max;
}
@Override
public void run() {
while (true) {
int ds=min+r.nextInt(max-min);
account.withdraw(ds);
try {
Thread.sleep(r.nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
如果想规定天数,需要设置一个静态变量day,然后进行判断结束循环,我这个代码是没结束的;