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();
}
}
运行结果:
你代码put和 print 是两个操作啊
可能
A线程 -PUT
B 线程 - PUT
A线程 -PRINT
B线程 - PRINT
LinkedBlockingQueue 只是保证同时只有一个线程在操作 这个队列
假设这种场景:
生产者已经将数据写入到队列,此时还没执行sout方法,然后此时消费者正好已经消费完一条数据,
此时生产者继续执行,打印总条数,是不是会出现数据总数本应该+1,但是数据总条数却不变的场景?