生产者-消费者示例无法运行,请求协助修复程序
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
- Added a shared data container for thread communication
- Implemented
synchronizedmethods +wait()/notify()to handle thread synchronization - Added graceful exit logic
- 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:
synchronizedmethods 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
Dataclass 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
相关产品推荐
相关产品推荐

