多线程 使用LinkBlockingQueue最好添加读写锁
以下示例,不加读写锁有可能线程C会出现输出为false的情况
添加以后则不会出现此种状况
package com.cy.BlockQueueDemo;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LinkBlockingQueueDemo {
private static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue();
private static ReentrantReadWriteLock.WriteLock writeLock = new ReentrantReadWriteLock().writeLock();
public static void main(String[] args) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName()+":"+queue.toString());
writeLock.lock();
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000);
queue.add(i);
System.out.println(Thread.currentThread().getName()+":"+queue.toString(