生产者消费者图形化演示Java实现
时间: 2023-10-16 11:24:48 浏览: 133
好的,这是一个简单的Java实现的生产者消费者图形化演示:
```java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ProducerConsumerDemo extends JFrame {
private static final long serialVersionUID = 1L;
private static final int BUFFER_SIZE = 10;
private static final int MAX_SLEEP_TIME = 3000;
private static final int MAX_PRODUCE_TIMES = 20;
private static final int MAX_CONSUME_TIMES = 20;
private Queue<Integer> buffer;
private JLabel bufferLabel;
public ProducerConsumerDemo() {
setTitle("Producer Consumer Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JLabel producerLabel = new JLabel("Producer");
producerLabel.setBounds(50, 50, 100, 30);
add(producerLabel);
JLabel consumer1Label = new JLabel("Consumer 1");
consumer1Label.setBounds(50, 100, 100, 30);
add(consumer1Label);
JLabel consumer2Label = new JLabel("Consumer 2");
consumer2Label.setBounds(50, 150, 100, 30);
add(consumer2Label);
bufferLabel = new JLabel();
bufferLabel.setBounds(200, 50, 100, 130);
add(bufferLabel);
buffer = new LinkedList<Integer>();
Producer producer = new Producer();
Consumer consumer1 = new Consumer(1);
Consumer consumer2 = new Consumer(2);
producer.start();
consumer1.start();
consumer2.start();
setVisible(true);
}
private class Producer extends Thread {
private Random random = new Random();
@Override
public void run() {
int count = 0;
while (count < MAX_PRODUCE_TIMES) {
int value = random.nextInt(100);
synchronized (buffer) {
while (buffer.size() == BUFFER_SIZE) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer.offer(value);
bufferLabel.setText(buffer.toString());
buffer.notifyAll();
}
count++;
try {
sleep(random.nextInt(MAX_SLEEP_TIME));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private class Consumer extends Thread {
private int id;
private Random random = new Random();
public Consumer(int id) {
this.id = id;
}
@Override
public void run() {
int count = 0;
while (count < MAX_CONSUME_TIMES) {
int value;
synchronized (buffer) {
while (buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
value = buffer.poll();
bufferLabel.setText(buffer.toString());
buffer.notifyAll();
}
System.out.println("Consumer " + id + " consumed " + value);
count++;
try {
sleep(random.nextInt(MAX_SLEEP_TIME));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new ProducerConsumerDemo();
}
}
```
在这个实现中,我们使用了Java的多线程机制来模拟生产者消费者问题。我们使用一个队列来充当缓冲区,并使用`synchronized`关键字来保证线程的同步和互斥。当缓冲区已满时,生产者线程将被阻塞,直到有空间可用为止;当缓冲区为空时,消费者线程将被阻塞,直到有数据可用为止。我们使用`wait()`和`notifyAll()`方法来实现这种同步机制。同时,我们还使用了Java的图形化界面来展示缓冲区的状态,以便更好地理解整个过程。
阅读全文