Pablo Fernandez
Pablo Fernandez

Reputation: 105258

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.

Upvotes: 2

Views: 77

Answers (1)

JB Nizet
JB Nizet

Reputation: 692081

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.

Upvotes: 4

Related Questions