2、 创建两个线程:会计和出纳,两个线程共享目标对象的money。每次调用线程money减去50。当money的值小于150时,线程会计结束自己的run()方法进入死亡状态;当money的值小于0时,线程出纳结束自己的run()方法进入死亡状态。
时间: 2024-02-23 19:58:00 浏览: 16
下面是一个简单的示例代码,实现了上述需求:
```java
public class Account {
private int money = 200;
public synchronized void withdraw(int amount) {
money -= amount;
}
public int getMoney() {
return money;
}
}
public class Accountant implements Runnable {
private Account account;
public Accountant(Account account) {
this.account = account;
}
public void run() {
while (account.getMoney() >= 150) {
account.withdraw(50);
System.out.println("Accountant withdraws 50, remaining " + account.getMoney());
}
System.out.println("Accountant stops working.");
}
}
public class Cashier implements Runnable {
private Account account;
public Cashier(Account account) {
this.account = account;
}
public void run() {
while (account.getMoney() >= 0) {
account.withdraw(50);
System.out.println("Cashier withdraws 50, remaining " + account.getMoney());
}
System.out.println("Cashier stops working.");
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account();
Accountant accountant = new Accountant(account);
Cashier cashier = new Cashier(account);
Thread t1 = new Thread(accountant);
Thread t2 = new Thread(cashier);
t1.start();
t2.start();
}
}
```
在这个示例中,我们定义了一个 `Account` 类,表示账本,其中包含了一个 `money` 变量和对 `money` 进行操作的两个方法:`withdraw` 和 `getMoney`。
`Accountant` 和 `Cashier` 类都实现了 `Runnable` 接口,表示它们可以作为线程的目标对象。在 `run` 方法中,它们不断地调用 `Account` 对象的 `withdraw` 方法,每次减去 50 元,并输出剩余的金额。当 `Account` 对象的 `money` 值小于 150 时,会计线程停止工作;当 `money` 值小于 0 时,出纳线程停止工作。
在 `Main` 类中,我们创建了一个 `Account` 对象以及一个会计线程和一个出纳线程,分别将它们传入线程的构造方法中,并启动这两个线程。