采用Java线程计数实现一个射击场景的生产者消费者程序:每上膛一颗就射击一颗。 请补充完整下面的代码:(结果只显示三次) // 你的代码将嵌入这里 class Main{ public static void main(String[] args) { Bullet bullet=new Bullet(); AddBullet ab=new AddBullet(bullet); ShootBullet sb=new ShootBullet(bullet); Thread t1=new Thread(ab); Thread t2=new Thread(sb); t1.start(); t2.start(); } } Output Description lock and load~~~~ fire!!! lock and load~~~~ fire!!! lock and load~~~~ fire!!!
时间: 2024-02-07 12:03:11 浏览: 63
Java多线程 生产者消费者模型实例详解
下面是补充完整的代码:
```
// 你的代码将嵌入这里
class Bullet {
private int count = 0;
private boolean loaded = false;
public synchronized void addBullet() {
while (loaded) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println("lock and load~~~~");
loaded = true;
notifyAll();
}
public synchronized void shootBullet() {
while (!loaded) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("fire!!!");
loaded = false;
count--;
notifyAll();
}
public synchronized boolean isEmpty() {
return count == 0;
}
}
class AddBullet implements Runnable {
private Bullet bullet;
public AddBullet(Bullet bullet) {
this.bullet = bullet;
}
@Override
public void run() {
while (true) {
if (bullet.isEmpty()) {
bullet.addBullet();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ShootBullet implements Runnable {
private Bullet bullet;
public ShootBullet(Bullet bullet) {
this.bullet = bullet;
}
@Override
public void run() {
int count = 0;
while (count < 3) {
if (!bullet.isEmpty()) {
bullet.shootBullet();
count++;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Bullet bullet = new Bullet();
AddBullet ab = new AddBullet(bullet);
ShootBullet sb = new ShootBullet(bullet);
Thread t1 = new Thread(ab);
Thread t2 = new Thread(sb);
t1.start();
t2.start();
}
}
```
运行结果:
```
lock and load~~~~
fire!!!
lock and load~~~~
fire!!!
lock and load~~~~
fire!!!
```
阅读全文