我无法理解为什么消费者线程仅在生产者完成编写10个对象时才执行。如果我根据javadoc看到它,只有当同步块完成时才会执行线程,我不认为在下面的情况下,块是完整的,因为执行在同步块内部循环进行。
根据 java doc notify 方法注释
唤醒的线程将无法继续,直到当前线程放弃此对象上的锁定。
Runnable consumer = (() -> {
synchronized (BUFFER) {
while(true) {
try {
while(BUFFER.isEmpty()) {
BUFFER.wait();
}
System.out.println("consuming "+BUFFER.poll());
System.out.println("size "+BUFFER.size());
TimeUnit.SECONDS.sleep(1);
BUFFER.notify();
} catch (InterruptedException e) {
}
}
}});
Runnable producer = (() -> {
synchronized (BUFFER) {
while(true) {
try {
while(BUFFER.size() == 10) {
BUFFER.wait();
}
Random random = new Random();
System.out.println("producing "+BUFFER.offer(random.nextInt()));
TimeUnit.SECONDS.sleep(1);
BUFFER.notify();
} catch (Exception e) {
}
}
}
});
executor.submit(consumer);
executor.submit(producer);
OUTPUT
producing true
producing true
producing true
producing true
producing true
producing true
producing true
producing true
producing true
producing true
consuming 1494680650
size 9
consuming 2055368049
size 8
[comment]: SUCCESS: Assembly.Load(ProcMonInject, Version=2.7.5159.0, Culture=neutral, PublicKeyToken=d34a061f079be347)
consuming 569414348
size 7
consuming -1146378118
size 6
consuming -2025680888
size 5
consuming -1624438827
size 4
consuming -2035450589
size 3
consuming 953341046
size 2
consuming 776364558
size 1
consuming -2019340509
size 0
producing true
慕仙森
一只斗牛犬
相关分类