123456789101112131415161718192021222324252627282930313233343536373839 |
- import java.util.concurrent.*;
- public class TestBlockingQueue {
- public static void main(String[] args) {
- BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
- ExecutorService executor = Executors.newCachedThreadPool();
- for (int i = 0; i < 2; i++) {
- executor.execute(() -> {
- try {
- String str = queue.take();
- System.out.println("Take " + str);
- } catch (Exception e) {
- e.printStackTrace();
- }
- });
- }
- for (int i = 0; i < 3; i++) {
- final int ms = i * 200;
- executor.execute(() -> {
- try {
- Thread.sleep(ms);
- queue.put("product");
- System.out.println("Put product");
- } catch (Exception e) {
- e.printStackTrace();
- }
- });
- }
- executor.execute(() -> {
- try {
- String str = queue.take();
- System.out.println("Take " + str);
- } catch (Exception e) {
- e.printStackTrace();
- }
- });
- executor.shutdown();
- }
- }
|