6

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)

rui
  • 11,015
  • 7
  • 46
  • 64
  • 4
    why not leave the "main thread" just terminate? If there are non-daemon threads running, the VM will not terminate them. – user85421 Jul 08 '10 at 12:40
  • I actually didn't want to use 100% CPU in the hanging thread. – rui Jul 08 '10 at 12:57
  • @Carlos Heuberger - I actually don't have access to the other threads. They're hidden behind the library I use. – rui Jul 08 '10 at 13:08

10 Answers10

13
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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • +1 - but beware of spurious wake-ups: you need a forever loop around the wait since it can spuriously (that is, for no reason) return. Catching InterruptedException also needed... it's a bigger one-liner, but probably the best (correct) solution – user85421 Jul 09 '10 at 07:58
  • I don't like this answer simply on the basis that you aren't actually waiting for anything. (still not down-voting though) – Tim Bender Jul 09 '10 at 09:11
  • @Tim Bender - I agree. I answered instinctively to "how to _hang_ a thread". :) – Bozho Jul 09 '10 at 09:55
  • Would it be better to wait on a dummy `Object` instance, instead of `this`? – kevinarpe Oct 16 '15 at 02:10
12

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.
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
krock
  • 28,904
  • 13
  • 79
  • 85
  • sorry if I'm wrong but using join() means that there is only two threads right? main program and listener. Whereas the OP wants listeners. – nanda Jul 08 '10 at 12:00
  • @nanda, the assumption (probably correct) is that the OP wants listeners so he can be notified when threads have finished executing whilst the main thread is in something like a `sleep()` loop waiting for this to happen. The extra callback work is not necessary if you use any of the answers given. – krock Jul 08 '10 at 12:16
  • 3
    Just loop over your threads and call join() for each one. Once one finishes the loop will join the next one. When your loop exits you can be sure that the last thread has exited. – Chris Nava Jul 08 '10 at 13:24
6

Thread.sleep(Long.MAX_VALUE);

Ok, so it isn't forever, but talk about a really long time :)

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
5

Use executor. By using method shutdown() you'll force the executor to wait until all threads are finished.

nanda
  • 24,458
  • 13
  • 71
  • 90
  • 1
    I agree, you should use the new concurrent package: http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/util/concurrent/package-summary.html – Davy Meers Jul 08 '10 at 11:52
  • then the main porgram will not 'hang' forever – Redlab Jul 08 '10 at 11:53
  • I bet the meaning of 'forever' that OP means is that the main program wait until all threads are finished. I might be wrong :) – nanda Jul 08 '10 at 11:56
  • I think you're wrong. It sounds like the OP wants to create a service that listens for messages and does something literally forever. An exit condition probably isn't even in the design. – Tim Bender Jul 09 '10 at 09:12
5

With a CountDownLatch you can wait untill the count down reached 0, if you make sure it never counts down, maybe only when it needs to end. (This also result in 0% cpu, the opposite of loops that will run forever, and with join() your app will still finish when all other threads finished, The option of the executor is better, but will also end when all executed task have finished)

Redlab
  • 3,110
  • 19
  • 17
3

You can use thread.join to wait for all of the threads.

NG.
  • 22,560
  • 5
  • 55
  • 61
1

Here is a solution that is a one-liner, in that you only have to add one extra line. (You do have to add synchronized and throws InterruptedException to your main declaration though.) Also, it does not need access to, or even knowledge of the threads in the library you are using.

public static synchronized void main(String[] args) throws InterruptedException{
  ...
  YourMainClass.class.wait();  // wait forever
}

It assumes you will never call notify on your main class and that you want to exit if you get an InterruptedException. (You can add a while (true) { ... } around the wait line if you really want to guard against that.)

Eamonn O'Brien-Strain
  • 3,352
  • 1
  • 23
  • 33
0

while(true) { Thread.sleep(1000); }

  • 2
    It is kind of wasteful and unintuitive to let the thread wake up every second just to put it to sleep again. See Tim Benders reply for a better approach using `Thead.sleep(long)`. – Zero3 Jan 06 '16 at 18:41
0
public static void main(String[] args) {
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
            }
        }
    };
    t.setDaemon(false);
    t.start();
}
Steve McLeod
  • 51,737
  • 47
  • 128
  • 184
-1
for(;;);

But it's very unlikely that hanging the thread is what you want. Instead, you should consider options like joining on the other threads.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539