采用Java 多线程技术,设计实现坖坔坙合生产者和消坕者问题的程序。对坖坔对象(枪膛)进行操坓,其最大坘量是12颗子弹。生产者线程是坖坔压入线程,它坒断向枪膛中压入子弹;消坕者线程是坖坔射出线程,它坒断从枪膛中射出子弹。
时间: 2023-06-16 19:06:52 浏览: 87
以下是一个Java多线程实现生产者消费者问题的示例代码:
```
public class Gun {
private int maxBullets = 12;
private int bullets = 0;
public synchronized void loadBullet() throws InterruptedException {
while (bullets == maxBullets) {
wait();
}
bullets++;
System.out.println("Loaded bullet, bullets in gun: " + bullets);
notifyAll();
}
public synchronized void shootBullet() throws InterruptedException {
while (bullets == 0) {
wait();
}
bullets--;
System.out.println("Shot bullet, bullets in gun: " + bullets);
notifyAll();
}
}
public class Producer implements Runnable {
private Gun gun;
public Producer(Gun gun) {
this.gun = gun;
}
public void run() {
try {
while (true) {
gun.loadBullet();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Consumer implements Runnable {
private Gun gun;
public Consumer(Gun gun) {
this.gun = gun;
}
public void run() {
try {
while (true) {
gun.shootBullet();
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
Gun gun = new Gun();
Producer producer = new Producer(gun);
Consumer consumer = new Consumer(gun);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
```
这个程序中,`Gun`类代表一个枪,`Producer`类代表生产者线程,`Consumer`类代表消费者线程。在`Gun`类中,`loadBullet()`方法代表生产者向枪中压入子弹,`shootBullet()`方法代表消费者从枪中射出子弹。这两个方法都使用`synchronized`关键字同步,确保线程安全。
在`Producer`和`Consumer`类的`run()`方法中,循环调用`Gun`类中对应的方法,实现生产者和消费者的功能。`Thread.sleep()`方法用于模拟生产和消费的时间间隔。
在`Main`类中,创建了一个`Gun`对象、一个`Producer`对象和一个`Consumer`对象,并分别将它们作为参数传入两个`Thread`对象中,分别启动生产者和消费者线程。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)