用java写一段程序,一块蛋糕有30g,两只蚂蚁轮流搬蛋糕,一只蚂蚁一次可以搬走2g,蚂蚁A搬走6g后蚂蚁B才开始搬,用多线程模拟两只蚂蚁搬完所有的蛋糕
时间: 2024-03-15 17:45:47 浏览: 179
一个小小的JAVA多线程程序
好的,以下是代码实现:
```java
public class AntCake {
private static final int CAKE_WEIGHT = 30;
private static final int ANT_CAPACITY = 2;
private static int cakeWeight = CAKE_WEIGHT;
public static void main(String[] args) {
Thread antA = new Thread(() -> {
int count = 0;
while (cakeWeight > 0) {
synchronized (AntCake.class) {
if (count < 3) {
if (cakeWeight >= ANT_CAPACITY) {
cakeWeight -= ANT_CAPACITY;
System.out.println("蚂蚁A搬走了" + ANT_CAPACITY + "g,还剩" + cakeWeight + "g");
count++;
AntCake.class.notify();
} else {
try {
AntCake.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
AntCake.class.notify();
break;
}
}
}
});
Thread antB = new Thread(() -> {
while (cakeWeight > 0) {
synchronized (AntCake.class) {
if (cakeWeight >= ANT_CAPACITY) {
cakeWeight -= ANT_CAPACITY;
System.out.println("蚂蚁B搬走了" + ANT_CAPACITY + "g,还剩" + cakeWeight + "g");
AntCake.class.notify();
} else {
try {
AntCake.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
antA.start();
antB.start();
}
}
```
程序中使用了两个线程分别模拟两只蚂蚁,使用了synchronized同步代码块和wait/notify机制来保证两只蚂蚁交替搬运蛋糕的顺序和保证线程安全。其中蚂蚁A在搬运前需要等待蚂蚁B搬运完一定数量的蛋糕后才能开始搬运,因此使用了一个计数器count来控制。同时当蛋糕数量为0时,线程退出。
阅读全文