使用queue作为线程间通信的方式,并wait()/notifyAll()

    1. package org.example.concurrency.test;
    2. import lombok.extern.slf4j.Slf4j;
    3. import java.util.LinkedList;
    4. import java.util.concurrent.TimeUnit;
    5. /**
    6. * @author huskyui
    7. */
    8. @Slf4j
    9. public class Test21 {
    10. public static void main(String[] args) {
    11. MessageQueue messageQueue = new MessageQueue(2);
    12. for (int i = 0;i<3;i++){
    13. Message message = new Message(i,"message"+i);
    14. new Thread(()->{
    15. messageQueue.put(message);
    16. },"生产者"+i).start();
    17. }
    18. new Thread(()->{
    19. while (true) {
    20. try {
    21. TimeUnit.SECONDS.sleep(2);
    22. } catch (InterruptedException e) {
    23. e.printStackTrace();
    24. }
    25. Message message = messageQueue.take();
    26. System.out.println(message);
    27. }
    28. },"消费者").start();
    29. }
    30. }
    31. @Slf4j
    32. class MessageQueue {
    33. private LinkedList<Message> list = new LinkedList<>();
    34. private int capacity;
    35. public MessageQueue(int capacity){
    36. this.capacity = capacity;
    37. }
    38. public Message take(){
    39. synchronized (list){
    40. while (list.isEmpty()){
    41. try {
    42. log.info("当前消息队列消息为空");
    43. list.wait();
    44. } catch (InterruptedException e) {
    45. e.printStackTrace();
    46. }
    47. }
    48. Message message = list.removeLast();
    49. log.info("接受消息");
    50. list.notifyAll();
    51. return message;
    52. }
    53. }
    54. public void put(Message message){
    55. synchronized (list){
    56. while (list.size() >= capacity){
    57. try {
    58. log.info("当前队列已满");
    59. list.wait();
    60. } catch (InterruptedException e) {
    61. e.printStackTrace();
    62. }
    63. }
    64. list.addFirst(message);
    65. log.info("放入信息{}",message);
    66. list.notifyAll();
    67. }
    68. }
    69. }
    70. class Message {
    71. private int id;
    72. private Object value;
    73. public int getId() {
    74. return id;
    75. }
    76. public Object getValue() {
    77. return value;
    78. }
    79. public Message(int id, Object value) {
    80. this.id = id;
    81. this.value = value;
    82. }
    83. @Override
    84. public String toString() {
    85. return "Message{" +
    86. "id=" + id +
    87. ", value=" + value +
    88. '}';
    89. }
    90. }