Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you hang a thread in Java in one line?

By one line I mean at most 100 chars per line.

(I basically need this to keep the program alive. The main thread registers callback listeners that are run in separate threads. I just need the main one to hang forever and let the other threads do their work)

like image 528
rui Avatar asked Jul 08 '10 11:07

rui


2 Answers

synchronized(this) {
    while (true) {
        this.wait();
    }
}

(thanks to Carlos Heuberger. Exception handling omitted in the above code)

This will make the current thread wait on the monitor of the current class until someone calls notify(), or forever.

like image 185
Bozho Avatar answered Oct 31 '22 16:10

Bozho


There are a few things you could do that would be better than hanging the initial thread forever:

  1. Use otherThread.join(). This will cause the current thread you are running in to sleep until the other thread has finished executing.
  2. As @nanda suggests, use ExcecutorService.shutdown() to wait until a pool of threads has finished.
  3. Use otherThread.setDaemon(false) and simply let your initial thread exit. This will set your new threads as user threads. Java will not shut down until the only threads running are daemon threads.
like image 45
krock Avatar answered Oct 31 '22 16:10

krock