Java thread wait and notify

浪尽此生 提交于 2019-12-03 12:09:57

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!)

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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!