简体   繁体   中英

Invoking code inside a thread that has already been started in java

How can I run code inside a custom thread that has already started?

I need it to run code inside a started thread like EDT-SwingUtilities.invokeLater() or Android.view.runOnUIThread() does.

Thanks!

In a nutshell, your special thread needs to keep a queue of tasks to run, then sit and wait for tasks to be added to that queue. When a task appears it should run the task, and then go back and wait for more. Be sure to use proper synchronization to protect that queue, since it will be accessed by multiple threads. And be very careful that exceptions don't accidentally terminate your loop.

This is, of course, exactly what the event dispatcher thread for a user interface does.

If you expect to be able to do this on a thread which is not otherwise dedicated to accepting tasks for execution, then the answer is simple: what you ask for is impossible. The only way to accomplish this is with explicit cooperation by the thread on which you want to do this.

If the above paragraph did not discourage you, then the best option is to use an ExecutorService and submit tasks to it. The service can be configured to be single-threaded, if that is your goal.

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