Thread.join() does not work when executing the Thread by ExecutorService

  • A+
Category:Languages

This is my code:

public static void main(String[] args) {         System.out.println("program started");         ExecutorService executor = Executors.newCachedThreadPool();         Thread thread = new Thread(new Runnable() {             @Override             public void run() {                 try {                     Thread.sleep(3000);                 } catch (InterruptedException e) {                     e.printStackTrace();                 }                 System.out.println("thread finished");             }         });         executor.execute(thread);         try {             thread.join();         } catch (Exception e) {             e.printStackTrace();         }         System.out.println("thread joined");      } 

When I start my Thread as showed above, thread.join() does not work and it does not wait for the Thread to be finished. I need to execute my Thread by a ExecutorService and also wait for that Thread to be finished. but my code does not work good. Can anyone help me?

Why I am not using Future instead of Thread?

because sometimes I need to interrupt my Thread and wait for that Thread to be finished. but when i cancel a Future, future.get() gets an Exception and does not wait for it's Thread to be finished.

I apologize in advance if the grammar of my sentence is not correct. because I can't speak English well.

 


Simple answer: don't do that.

Do not mix layers of abstractions like this. The Executor interface doesn't execute() threads. It takes Runnables. It doesn't matter that you pass a Thread object to it, your thread will not be used at all, besides a call to the run() method.

Mixing "low layer" bare iron threads with an abstracted Executor service is simply a bad idea.

The whole point of that thread pool concept is that you do not try to control the underlying threads. There is simply no point in waiting for a pooled thread to end. A thread pool keeps threads around, because establishing threads is a (relatively) costly operations. So they don't end, but live on, to do other work in the future.

The real answer here: either don't use that executor service, or look for a solution that works with that concept (without you going in and doing low level stuff on the side).

And the "real real" answer: step back, and tell us about the "real" problem you intent to solve this way.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: