Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to keep the main method running

I used a way to keep the main method running.

public static void main(String[] args) throws InterruptedException {
    while (true) {
        TimeUnit.SECONDS.sleep(1);
    }
}

But I'm not sure it's the best way.

Can someone give me some advice?

like image 485
dai Avatar asked Nov 26 '22 20:11

dai


1 Answers

The best way is to hold the main() Thread without entering into Terminated/Dead state. Below are the two methods I often use-

 public static void main(String[] args) throws InterruptedException {

    System.out.println("Stop me if you can");
   Thread.currentThread().join(); // keep the main running
  }

The other way is to create the ReentrantLock and call wait() on it:

public class Test{
private static Lock mainThreadLock = new ReentrantLock();

public static void main(String[] args) throws InterruptedException {

    System.out.println("Stop me if you can");
    synchronized (mainThreadLock) {
        mainThreadLock.wait();
     }
}
like image 68
Madhu Stv Avatar answered Nov 29 '22 10:11

Madhu Stv