没有容量, 进去一个元素,必须等待取出来之后,才能再往里面放一个元素!

    put、take

    1. import java.sql.Time;
    2. import java.util.concurrent.BlockingQueue;
    3. import java.util.concurrent.SynchronousQueue;
    4. import java.util.concurrent.TimeUnit;
    5. /**
    6. * 同步队列
    7. * 和其他的BlockingQueue 不一样, SynchronousQueue 不存储元素
    8. * put了一个元素,必须从里面先take取出来,否则不能在put进去值!
    9. */
    10. public class SynchronousQueueDemo {
    11. public static void main(String[] args) {
    12. BlockingQueue<String> blockingQueue = new SynchronousQueue<>(); // 同步队列
    13. new Thread(()->{
    14. try {
    15. System.out.println(Thread.currentThread().getName()+" put 1");
    16. blockingQueue.put("1");
    17. System.out.println(Thread.currentThread().getName()+" put 2");
    18. blockingQueue.put("2");
    19. System.out.println(Thread.currentThread().getName()+" put 3");
    20. blockingQueue.put("3");
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. }
    24. },"T1").start();
    25. new Thread(()->{
    26. try {
    27. TimeUnit.SECONDS.sleep(3);
    28. System.out.println(Thread.currentThread().getName()+"=>"+blockingQueue.take());
    29. TimeUnit.SECONDS.sleep(3);
    30. System.out.println(Thread.currentThread().getName()+"=>"+blockingQueue.take());
    31. TimeUnit.SECONDS.sleep(3);
    32. System.out.println(Thread.currentThread().getName()+"=>"+blockingQueue.take());
    33. } catch (InterruptedException e) {
    34. e.printStackTrace();
    35. }
    36. },"T2").start();
    37. }
    38. }
    1. T1 put 1
    2. T2=>1
    3. T1 put 2
    4. T2=>2
    5. T1 put 3
    6. T2=>3