我正在用 Java 实现消费者-生产者问题,我需要为此添加人。我的问题是从Customer
或Producer
类更改 UI 组件。
我不知道如何从其他不相关的类中调用这些组件。当我试图获得例如height
组件时,一切都像魅力一样,但是当我尝试set
任何事情时,什么都没有发生!
这是我的Producer
课程代码,经过了一些尝试:
public class Producer extends Thread {
// Variable which holds shared queue
private BlockingQueue<String> queue;
// Amount products created by producer
private int steps;
// Object with normaln distribution
private NormalDistribution distribution;
// Accessors to the frame
private PCPMainFrame frame;
private JSlider queueSlider;
private JProgressBar queueProgressBar;
// Constructor with 4 arguments
// q - is our queue shared between customer and producer
// steps - amount of products
// mean - parameter rquired for normal distribution
// standardDeviation - ditto
public Producer(BlockingQueue<String> q, int steps, double mean, double standardDeviation){
this.queue=q;
this.steps = steps;
this.distribution = new NormalDistribution(mean, standardDeviation);
this.frame = new PCPMainFrame();
this.queueSlider = frame.getQueueSlider();
this.queueProgressBar = new JProgressBar();
}
@Override
public void run() {
// Generating products and filling queue with them
for(int i = 0; i < steps; i++){
try {
long sleepTime = Math.abs((long)distribution.sample()*100);
Thread.sleep(sleepTime);
// Saving element in queue
queue.put(String.valueOf(i));
// This is a log for developer needs, feel free to uncomment
System.out.println("Produced: " + i);
queueSlider.setValue(steps);
frame.setQueueProgressBar(queueProgressBar);
} catch (InterruptedException e) {
System.out.println("Producer exception: " + e);
}
}
// Ading exit message at the end of the queue
String exit = new String("exit");
try {
queue.put(exit);
} catch (InterruptedException e) {
System.out.println("Queue exception: " + e);
}
}
}