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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With