public class Test {
private int queueSize = 10;
private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(queueSize);
public static void main(String[] args) {
Test test = new Test();
Producer producer = test.new Producer();
Consumer consumer = test.new Consumer();
producer.start();
consumer.start();
}
class Consumer extends Thread {
@Override
public void run() {
while (true) {
try {
queue.take();
System.out.println("Consumer : queue.size = " + queue.size());
} catch (InterruptedException e) {
}
}
}
}
class Producer extends Thread {
@Override
public void run() {
while (true) {
try {
queue.put(1);
System.out.println("Producer : queue.size = " + queue.size());
} catch (InterruptedException e) {
}
}
}
}
}
使用阻塞队列无需单独考虑同步和线程间通信的问题,实现起来很简单