java中的BlockingQueue是线程安全的,这是共识。但是求看如下代码哪里有问题?为啥运行结果会出现这个现象?
package JUC;
import java.util.concurrent.*;
public class TestJUC {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(3);
new Thread(() -> {
// 生产者只管生产产品
for (int i = 0; i < 34; i++) {
try {
blockingQueue.put(Thread.currentThread().getName() + i);
System.out.println("【" + Thread.currentThread().getName() + "】----放入----了" + Thread.currentThread().getName()
+ i + "现在blockingQueue大小为" + blockingQueue.size());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
}, "生产者A").start();
new Thread(() -> {
// 生产者只管生产产品
for (int i = 34; i < 67; i++) {
try {
blockingQueue.put(Thread.currentThread().getName() + i);
System.out.println("【" + Thread.currentThread().getName() + "】----放入----了" + Thread.currentThread().getName()
+ i + "现在blockingQueue大小为" + blockingQueue.size());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
}, "生产者B").start();
new Thread(() -> {
// 生产者只管生产产品
for (int i = 67; i < 100; i++) {
try {
blockingQueue.put(Thread.currentThread().getName() + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("【" + Thread.currentThread().getName() + "】----放入----了" + Thread.currentThread().getName()
+ i + "现在blockingQueue大小为" + blockingQueue.size());
}
}, "生产者C").start();
new Thread(() -> {
// 消费者,只管一直消费
for (int i = 0; i < 100; i++) {
try {
Object take = null;
take = blockingQueue.take();
System.out.println("线程【" + Thread.currentThread().getName() + "】---消费了---元素:" + take + "现在blockingQueue大小为" + blockingQueue.size());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
}, "消费者A").start();
}
}
运行结果: