How do you embed a stream in Java on one line?

On one line, I mean no more than 100 characters per line.

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

+6
java multithreading
source share
10 answers

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

  • Use otherThread.join() . This will cause the current thread that you start to be on until another thread completes execution.
  • As @nanda suggests, use ExcecutorService.shutdown () to wait for the thread pool to complete.
  • Use otherThread.setDaemon(false) and just let your initial thread exit. This will create new threads as custom threads. Java will not close until only threads executed by threads are daemon threads.
+12
source share
 synchronized(this) { while (true) { this.wait(); } } 

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

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

+13
source share

Thread.sleep(Long.MAX_VALUE);

Good, so it's not forever, but talk about a really long time :)

+6
source share

Use an artist. Using the shutdown () method, you will force the worker to wait for all threads to complete.

+5
source share

With CountDownLatch, you can wait until the counter reaches 0, if you make sure that it never counts, maybe only when it needs to be finished. (This also leads to 0% cpu, the opposite of loops that will run forever, and with join () your application will still end when all the other threads have finished. The executor option is better, but will also end when all the tasks completed)

+4
source share

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

+3
source share

Here is a solution that is single-line as you only need to add one extra line. (You need to add synchronized and throws InterruptedException to your main declaration.) In addition, it does not need access or even knowledge of the threads in the library you use.

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

It is assumed that you will never call notify in your main class and that you want to exit if you get an InterruptedException . (You can add while (true) { ... } around the wait line if you really want to protect against this.)

+1
source share
 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(); } 
0
source share

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

0
source share
 for(;;); 

But it is very unlikely that thread freezing is what you want. Instead, you should consider options such as combining other threads.

-one
source share

All Articles