发布网友 发布时间:2022-05-01 07:48
共4个回答
热心网友 时间:2023-10-09 20:03
你的思路基本是正确的,只是你实现代码的时候大意了,没有考虑整体的流程,我帮你修改好了,代码如下:
package com.ifly.classpractice.day8_8.procerconsumer2;
public class ProcerConsumer {
public static int count;
public static void main(String[] args) throws InterruptedException {
Object mutex = new Object();
new Consumer(mutex).start();
new Procer(mutex).start();
}
}
class Procer extends Thread {
private Object mutex;
public Procer(Object mutex) {
this.mutex = mutex;
}
@Override
public void run() {
synchronized (mutex) {
while (true) {
while (ProcerConsumer.count > 0) {
mutex.notify();
try {
sleep(500) ;
System.out.println("仓库已满,正等待消费...");
mutex.wait();
} catch (InterruptedException e1) {
System.out.println("中间环节出错,停止制造汽车");
}
}
ProcerConsumer.count++;
System.out.println("+procer " + ProcerConsumer.count);
}
}
}
}
class Consumer extends Thread {
private Object mutex;
public Consumer(Object mutex) {
this.mutex = mutex;
}
@Override
public void run() {
synchronized (mutex) {
while (true) {
while (ProcerConsumer.count == 0) {
mutex.notify();
try {
sleep(500) ;
System.out.println("仓库已空,正等待生产...");
mutex.wait();
} catch (InterruptedException e) {
System.out.println("中间环节出错,停止制造汽车");
}
}
ProcerConsumer.count--;
System.out.println("-Consumer " + ProcerConsumer.count);
}
}
}
}
热心网友 时间:2023-10-09 20:03
你需要解决什么?是看不懂你贴的那段代码么追问代码是我自己写的,但是运行不通过啊,我需要仓库中有汽车时就可以销售,但是该程序都是先生产好,才能销售
热心网友 时间:2023-10-09 20:04
我这边有个,可以发给你追问发来看看啊,是不是多生产者和多消费者?追答//共享资源类
class SharedData{
private char c;
private boolean isProced=false;
//同步方法putShareChar
public synchronized void putShareChar(char c){
if(isProced){
try {
System.out.println("消费者还未消费,因此停止生产");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.c=c;
isProced=true;
notify();
System.out.println("生产了产品"+c+"通知消费者消费。。。");
}
//同步方法getShareChar
public synchronized char getShareChar(){
if(!isProced){
try {
System.out.println("生产者还未生产,因此消费者停止消费");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isProced=false;
notify();
System.out.println("消费者消费了产品"+c+"通知生产者生产。。。");
return this.c;
}
}
//生产者线程类
class Procer extends Thread{
private SharedData s;
Procer(SharedData s){
this.s=s;
}
public void run(){
for(char ch='A';ch<='D';ch++){
try {
Thread.sleep((int)(Math.random()*3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
s.putShareChar(ch);
}
}
}
太长了,发不完。。
热心网友 时间:2023-10-09 20:04
问题?这段代码有啥问题