Java thread wait and notify

后端 未结 2 2036
暖寄归人
暖寄归人 2021-02-14 07:28

I have two threads. Thread A is pulling some elements from queue and thread B is adding some elements to the queue.

I want thread A to go to sleep when the queue is emp

相关标签:
2条回答
  • 2021-02-14 08:22

    Use a BlockingQueue, which is:

    A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

    Seriously, don't try to reinvent the wheel here.




    (If you must use wait/notify, read this tutorial. But spare yourself the pain, please!)

    0 讨论(0)
  • 2021-02-14 08:22

    Here are some details:

    import java.concurrent.Executors;
    import java.concurrent.ExecutorService;
    ...
    ExecutorService executor = Executors.newFixedThreadPool(someNumberOfThreads);
    ...
    executor.execute(someObjectThatImplementsRunnable);
    ...
    executor.shutdownNow();
    

    That's all there is to it with Java's newer threading capabilities. Executor is a thread pool with someNumberOfThreads in it. It is fed by a blocking queue. All the threads sleep unless there is work to do. When you push a Runnable object into the queue using the execute() method, the Runnable object sits in the queue until there is a thread available to process it. Then, it's run() method is called. Finally, the shutdownNow() method signals all threads in the pool to shutdown.

    It's much simpler now than it used to be.

    (There are lots of variations on this, such as pools with minimum and maximum numbers of threads, or queues which have maximum sizes before threads calling execute() will block.)

    0 讨论(0)
提交回复
热议问题