java实现应用多线程同步机制,模拟生产者消费者问题。
时间: 2024-04-29 18:22:49 浏览: 95
生产者消费者问题是一个经典的多线程同步问题,Java提供了多种方式来实现线程间的同步,如synchronized、Lock、Semaphore等。下面是一种使用synchronized实现的生产者消费者问题的示例代码:
```java
import java.util.LinkedList;
public class ProducerConsumer {
private static final int BUFFER_SIZE = 10;
private LinkedList<Integer> buffer = new LinkedList<>();
private Object lock = new Object();
public void produce() throws InterruptedException {
while (true) {
synchronized (lock) {
while (buffer.size() == BUFFER_SIZE) {
lock.wait();
}
int value = (int) (Math.random() * 100);
buffer.addLast(value);
System.out.println("Produced " + value);
lock.notifyAll();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (lock) {
while (buffer.isEmpty()) {
lock.wait();
}
int value = buffer.removeFirst();
System.out.println("Consumed " + value);
lock.notifyAll();
Thread.sleep(1000);
}
}
}
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
// create producer thread
Thread producer = new Thread(() -> {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// create consumer thread
Thread consumer = new Thread(() -> {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// start threads
producer.start();
consumer.start();
}
}
```
在上述示例中,生产者和消费者共享一个缓冲区buffer,当缓冲区已满时,生产者线程进入等待状态,当缓冲区为空时,消费者线程进入等待状态。通过使用synchronized关键字和wait()、notifyAll()方法,实现了线程的同步。其中lock对象用来控制线程的互斥访问,wait()方法使线程进入等待状态,notifyAll()方法用来唤醒等待的线程。生产者和消费者线程通过循环不断地生产和消费数据,直到程序被终止。
阅读全文