public class NotifyDemo_BlockingQ {
public static void main(String[] args) {
Data data = new Data();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 10000; i++) {
data.consu();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "aaa").start();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 10000; i++) {
data.produ();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "bbb").start();
}
}
class Data {
// BlockingQueue<String> queue = new SynchronousQueue<String>();
BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void consu() throws InterruptedException {
lock.lock();
try {
if (queue.size() == 1) {
condition.await();
}
System.out.println("生产结果" + queue.offer("生产", 1, TimeUnit.SECONDS));
condition.signalAll();
} finally {
lock.unlock();
}
}
public void produ() throws InterruptedException {
lock.lock();
try {
// String take = queue.take();
if (queue.size() == 0){
condition.await();
}
String take = queue.poll(1, TimeUnit.SECONDS);
System.out.println("take:" + take);
condition.signalAll();
} finally {
lock.unlock();
}
}
}
尝试了一下,第一次想用SynchronousQueue,结果出了问题,最后换成arrayblockingqueue;
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产
生产结果true
take:生产