简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM