简体   繁体   中英

How does java.util.concurrent classes reuse threads?

I'm talking about the Thread instances, if they get their Runnable provided as a constructor argument and you can only execute their start method once, how come the Executor* family of classes reuse them?

PS: I know and use the Executors classes which are nicer abstraction than bare threads, I'm asking this just out of curiosity.

The runnables (lets call them R) passed to executor threads are in fact wrapped inside other runnables (let's call them W). The pseudo-code of the run() method of W is

while (threadMustRun) {
    wait for new R to be submitted and assigned to this thread
    execute R.run()
}

It's actually more complex than that, but you should get the idea. To really understand what it does, look at the code the the ThreadPoolExecutor.Worker inner class.

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