采用Java线程计数实现一个射击场景的生产者消费者程序:每上膛一颗就射击一颗。
请补充完整下面的代码:(结果只显示三次)
Output Description
// 你的代码将嵌入这里
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!!!
源码
class Bullet implements Runnable { public static int count = 3;//子弹总数 public static Bullet bu;//锁 public static Boolean status = Boolean.FALSE;//枪里是否有子弹 @Override public void run() { } } class AddBullet extends Bullet { public AddBullet(Bullet bullet) { bu = bullet; } @Override public void run() { while (true) {//循环 synchronized (bu) {//同步代码块 if (count == 0) {//循环终止条件 break; } else {//循环继续条件 if (status) { try {//枪里有子弹 bu.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } else {//枪里没有子弹 System.out.println("lock and load~~~~");//上子弹 status=Boolean.TRUE;//状态改为有子弹 bu.notifyAll();//唤醒其他进程 } } } } } } class ShootBullet extends Bullet { public ShootBullet(Bullet bullet) { bu = bullet; } @Override public void run() { synchronized (bu) { while (true) { synchronized (bu) { if (count == 0) { break; } else { if (!status) { try { bu.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { System.out.println("fire!!!"); count--; status = Boolean.FALSE; bu.notifyAll(); } } } } } } } // 你的代码将嵌入这里 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(); } }