以下代码是单线程间通信示例
    但是如果应用在多线程中会存在诸如一下问题

    1. LinkedList数据为空时,执行removeFirst方法
    2. LinkedList元素为10时,执行addLast方法 ```java import org.w3c.dom.events.Event; import sun.management.counter.perf.PerfInstrumentation;

    import java.util.LinkedList; import java.util.concurrent.TimeUnit;

    public class EventQueue { private final int max;

    1. static class Event {
    2. }
    3. private final LinkedList<Event> eventQueue = new LinkedList<>();
    4. private final static int DEFAULT_MAX_EVENT = 10;
    5. public EventQueue() {
    6. this(DEFAULT_MAX_EVENT);
    7. }
    8. public EventQueue(int max) {
    9. this.max = max;
    10. }
    11. public void offer(Event event) {
    12. synchronized (eventQueue) {
    13. if (eventQueue.size() >= max) {
    14. console("the queue is full.");
    15. try {
    16. eventQueue.wait();
    17. } catch (InterruptedException e) {
    18. e.printStackTrace();
    19. }
    20. }
    21. console("the new event is submitted");
    22. eventQueue.addLast(event);
    23. eventQueue.notify();
    24. }
    25. }
    26. public Event take() {
    27. synchronized (eventQueue) {
    28. if (eventQueue.isEmpty()) {
    29. console("the queue is empty");
    30. try {
    31. eventQueue.wait();
    32. } catch (InterruptedException e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. Event event = eventQueue.removeFirst();
    37. this.eventQueue.notify();
    38. console("the event " + event + "is handle");
    39. return event;
    40. }
    41. }
    42. private void console(String message) {
    43. System.out.printf("%s:%s\n", Thread.currentThread().getName(), message);
    44. }
    45. public static void main(String[] args) {
    46. final EventQueue eventQueue = new EventQueue();
    47. new Thread(() -> {
    48. for (; ; ) {
    49. eventQueue.offer(new EventQueue.Event());
    50. }
    51. }, "Producer").start();
    52. new Thread(() -> {
    53. for (; ; ) {
    54. eventQueue.take();
    55. try {
    56. TimeUnit.SECONDS.sleep(10);
    57. } catch (InterruptedException e) {
    58. e.printStackTrace();
    59. }
    60. }
    61. }, "Consumer").start();
    62. }

    }

    ``` 改进为多线程通信可用
    改进点:

    1. 将if判断改为while
    2. 将notify更改为notifyAll即可