TestBlockingQueue.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import java.util.concurrent.*;
  2. public class TestBlockingQueue {
  3. public static void main(String[] args) {
  4. BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
  5. ExecutorService executor = Executors.newCachedThreadPool();
  6. for (int i = 0; i < 2; i++) {
  7. executor.execute(() -> {
  8. try {
  9. String str = queue.take();
  10. System.out.println("Take " + str);
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. });
  15. }
  16. for (int i = 0; i < 3; i++) {
  17. final int ms = i * 200;
  18. executor.execute(() -> {
  19. try {
  20. Thread.sleep(ms);
  21. queue.put("product");
  22. System.out.println("Put product");
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. });
  27. }
  28. executor.execute(() -> {
  29. try {
  30. String str = queue.take();
  31. System.out.println("Take " + str);
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. });
  36. executor.shutdown();
  37. }
  38. }