You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生产者-消费者示例无法运行,请求协助修复程序

Hey there! Let's figure out why your producer-consumer setup isn't working right. From what you've shared, the main missing pieces are thread synchronization and a shared buffer to safely pass data between the Producer and Consumer—without these, the two threads can't coordinate properly. Here's a fixed, complete version of your code with clear explanations:


Core Issues Fixed

  1. Added a shared data container for thread communication
  2. Implemented synchronized methods + wait()/notify() to handle thread synchronization
  3. Added graceful exit logic
  4. Ensured threads don't waste resources with unnecessary polling

1. Shared Data Class (Communication Bridge)

This class acts as the safe buffer between your producer and consumer:

package Test1;

// Shared data container to pass length/width between threads
class Data {
    private int length;
    private int width;
    private boolean hasData = false; // Flag to track if data is ready for consumption

    // Producer writes data here
    public synchronized void put(int length, int width) {
        // Wait if buffer already has unconsumed data
        while (hasData) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
        this.length = length;
        this.width = width;
        hasData = true;
        notify(); // Tell consumer data is ready
    }

    // Consumer reads data here
    public synchronized int[] get() {
        // Wait if buffer is empty
        while (!hasData) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return null;
            }
        }
        hasData = false;
        notify(); // Tell producer buffer is empty
        return new int[]{length, width};
    }
}

2. Fixed Producer Class

Now it feeds input into the shared buffer instead of holding data locally:

package Test1;

import java.util.Scanner;

public class Producer extends Thread {
    private final Data sharedData;
    private final Scanner scan = new Scanner(System.in);

    // Inject shared data via constructor
    public Producer(Data sharedData) {
        this.sharedData = sharedData;
    }

    @Override
    public void run() {
        try {
            while (true) {
                System.out.print("Enter length (negative to exit): ");
                int length = scan.nextInt();
                System.out.print("Enter width (negative to exit): ");
                int width = scan.nextInt();

                // Send data to consumer
                sharedData.put(length, width);

                // Exit condition: stop if either value is negative
                if (length < 0 || width < 0) break;
            }
        } finally {
            scan.close();
        }
    }
}

3. Fixed Consumer Class

Now it pulls data from the shared buffer and calculates area:

package Test1;

public class Consumer extends Thread {
    private final Data sharedData;

    // Inject shared data via constructor
    public Consumer(Data sharedData) {
        this.sharedData = sharedData;
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                int[] dimensions = sharedData.get();
                if (dimensions == null) break;

                int length = dimensions[0];
                int width = dimensions[1];

                // Exit if producer sent negative values
                if (length < 0 || width < 0) break;

                int area = length * width;
                System.out.printf("Calculated Area: %d × %d = %d%n", length, width, area);
            }
        } finally {
            System.out.println("Consumer thread stopped.");
        }
    }
}

4. Main Class to Launch Threads

package Test1;

public class ProducerConsumerMain {
    public static void main(String[] args) {
        // Create single shared data instance for both threads
        Data sharedData = new Data();

        Producer producer = new Producer(sharedData);
        Consumer consumer = new Consumer(sharedData);

        producer.start();
        consumer.start();

        // Wait for producer to finish, then clean up consumer
        try {
            producer.join();
            consumer.interrupt();
            consumer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Program finished.");
    }
}

Key Improvements Explained

  • Thread Safety: synchronized methods ensure only one thread accesses the buffer at a time, preventing race conditions.
  • Efficient Coordination: wait()/notify() eliminate busy waiting—threads only wake up when there's work to do.
  • Clear Communication: The shared Data class centralizes all data passing logic, making the code easier to maintain.
  • Graceful Exit: Negative input triggers a clean shutdown for both threads.

内容的提问来源于stack exchange,提问作者Salil Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:14:08