简体   繁体   中英

How to schedule tasks in a specific thread without using a looper and a handler?

Timer creates its own thread and ScheduledThreadPoolExecutor uses a pool. Is their a way to specify the thread where the task will be executed directly without having to marshal any code? And if this is a bad idea, please explain why (beside the thread being busy).

I have no problem with the looper-handler approach, I'm just curious.

You can create a ScheduledThreadPoolExecutor with one single thread using Executors.newSingleThreadScheduledExecutor() .

Optionally, you can pass a ThreadFactory as parameter if you want to have more control about this single thread. The thread factory's newThread(Runnable) method is called every time the executor wants to have a new Thread instance that should run the given Runnable (which is not identical to the Runnable you pass to the executor's execute(...) , submit(...) or schedule(...) methods).

Note that you are not able to reuse an existing thread, as there is no way to 'inject' code into an already running thread in general, as it is possible in Qt . There, every thread has its own event queue and timing facility, so you can freely decide which (already existing) thread should process your timed task (see Timers in Qt ).

There is no such feature in Java out of the box.

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