开发者

How to make multiple threads that never stop running in a limited pool

开发者 https://www.devze.com 2023-04-10 11:21 出处:网络
I\'ve been trying to find out how can I run in a kind of executor service a few threads that won\'t leave the run() method while there is someone c开发者_如何学Pythononnected to them throught a socket

I've been trying to find out how can I run in a kind of executor service a few threads that won't leave the run() method while there is someone c开发者_如何学Pythononnected to them throught a socket channel.

The executor service could solve my problem if it rotate over the whole pool instead of waiting the method run stops.

Example: I have 200 threads, and I want to run it all in a limited pool of 20 threads.

Any tip?


Any compliant, pooling ExecutorService implementation already does this. It will not reuse a thread until the run() method of the callable/runnable has finished running. When a thread becomes available, that thread will be used to launch the next queued task.

List<Runnable> myTasks = new ArrayList<Runnable>();
//...add 200 runnables to myTasks...

ExecutorService threadPoolService = Executors.newFixedThreadPool(20);
for ( Runnable task : myTasks ) {
    threadPoolService.submit(task);
}

Edit

If @BalusC's interpretation of your question is correct, it seems like you are looking for something like coroutines. There is no support for that in Java. I think what you should be looking into is non-blocking I/O; however you should know that most real-world servers can handle 200 simultaneous threads no problem (since most of them will be blocking at any given time).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号