实现生产者、消费者的3种实现方式

编程

  1. synchronized + wait + notify 使用一个数组保存。数组为空生产者运行,然后调用notify唤醒消费者,自己等待。消费者完成消费,唤醒生产者,自己等待。

  2. ReentrantLock重入锁。

  3. BlockingQueue 底层还是使用了ReentrantLock

  • https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/BlockingQueue.html

Special value列:如果队列满了或者空了,操作会失败。返回值是操作结果

block列:如果队列满了或者是空,就会等待

Throws exception列:如果队列满了或者是空就会抛出异常

public class WaitConsumerProducer {

private String[] list = new String[10];

private int cursor = -1;

public void produce() throws InterruptedException {

synchronized (this) {

if (cursor >= 0) {

this.wait();

}

while (cursor < list.length - 1) {

list[++cursor] = "生产" + cursor;

}

this.notifyAll();

}

}

public void consume() throws InterruptedException {

synchronized (this) {

if (cursor < 0) {

this.wait();

}

while (cursor >= 0) {

System.out.println(list[cursor--]);

}

Thread.sleep(1000);

this.notifyAll();

}

}

}

public class ReentrantConsumerProducer {

private String[] list = new String[10];

private int cursor = -1;

private ReentrantLock lock = new ReentrantLock();

public void produce() {

lock.lock();

try {

// 放在 lock 前面就会死锁了

if (cursor >= 0) {

return;

}

while (cursor < list.length - 1) {

list[++cursor] = "商品" + cursor;

}

} finally {

lock.unlock();

}

}

public void consume() {

lock.lock();

try {

// 放在 lock 前面就会死锁了

if (cursor < 0) {

return;

}

while (cursor >= 0) {

Thread.sleep(200);

System.out.println(list[cursor--]);

}

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

lock.unlock();

}

}

}

public static void blockingQueue() {

final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();

new Thread(() -> {

while (true) {

try {

queue.put("商品");

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}).start();

new Thread(() -> {

while (true) {

try {

Thread.sleep(1000);

System.out.println(queue.take());

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}).start();

}

以上是 实现生产者、消费者的3种实现方式 的全部内容, 来源链接: utcz.com/z/514729.html

回到顶部