22.实现一个生产者-消费者问题,使用Java的线程同步机制。
生产者-消费者问题是一个经典的并发编程问题,其中生产者产生数据(或产品),消费者消费这些数据。在Java中,我们可以使用wait()
和notify()
方法或者BlockingQueue
接口来实现线程同步。
以下是使用wait()
和notify()
方法实现的生产者-消费者问题的示例:
java复制代码
public class ProducerConsumerExample { | |
private static final int MAX_SIZE = 10; // 缓冲区大小 | |
private static final Object lock = new Object(); // 锁对象 | |
private static List<Integer> buffer = new ArrayList<>(MAX_SIZE); // 缓冲区 | |
private static int count = 0; // 缓冲区中当前元素的数量 | |
// 生产者线程 | |
static class Producer extends Thread { | |
public void run() { | |
while (true) { | |
synchronized (lock) { | |
// 等待缓冲区不满 | |
while (count == MAX_SIZE) { | |
try { | |
lock.wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
// 生产一个产品(这里用随机数表示) | |
int product = (int) (Math.random() * 100); | |
buffer.add(product); | |
count++; | |
// 通知可能等待的消费者线程 | |
lock.notifyAll(); | |
} | |
// 休眠一段时间,模拟生产速度 | |
try { | |
Thread.sleep(100); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
// 消费者线程 | |
static class Consumer extends Thread { | |
public void run() { | |
while (true) { | |
synchronized (lock) { | |
// 等待缓冲区不空 | |
while (count == 0) { | |
try { | |
lock.wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
// 消费一个产品 | |
int product = buffer.remove(0); | |
count--; | |
// 通知可能等待的生产者线程 | |
lock.notifyAll(); | |
} | |
// 休眠一段时间,模拟消费速度 | |
try { | |
Thread.sleep(200); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
// 创建并启动生产者线程 | |
new Producer().start(); | |
// 创建并启动消费者线程 | |
new Consumer().start(); | |
} | |
} |
在上面的代码中,我们定义了一个Producer
类和一个Consumer
类,它们分别继承了Thread
类并重写了run()
方法。生产者会向缓冲区中添加产品,而消费者会从缓冲区中取出产品。我们使用一个共享的lock
对象来实现同步,以及wait()
和notifyAll()
方法来协调生产者和消费者之间的操作。
注意,在生产者和消费者的run()
方法中,我们使用了一个while
循环来检查缓冲区是否满或空,而不是if
条件判断。这是因为wait()
方法可能会因为其他原因(如interrupt()
)被唤醒,所以我们需要再次检查条件是否满足。
此外,为了避免死锁和活锁,确保在wait()
和notify()
方法调用前后都持有锁。这是因为在调用wait()
方法时,线程会释放锁,而notify()
或notifyAll()
方法调用后,其他线程可能会获取锁并继续执行。
尽管上述示例展示了如何使用基本的线程同步机制实现生产者-消费者问题,但在实际开发中,通常更推荐使用Java并发包中的BlockingQueue
接口及其实现类(如ArrayBlockingQueue
、LinkedBlockingQueue
等),因为它们提供了更简洁、更安全的线程同步机制。