保持main方法运行的最佳方法

时间:2018-03-22 07:40:38

标签: java main

我使用了一种方法来保持主方法的运行。

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

但我不确定这是最好的方式。

有人可以给我一些建议吗?

4 个答案:

答案 0 :(得分:0)

最好的方法是保持main()线程而不进入Terminated / Dead状态。 以下是我经常使用的两种方法-

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

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

另一种方法是创建ReentrantLock并在其上调用wait():

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();
     }
}

答案 1 :(得分:-1)

您应该使用ExecutorService并提交等待阅读服务输出的任务。

package demo;

import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class TaskDemo {
    public static void main(String[] args ) {
        System.out.println("Hello");

        ExecutorService threadPool = Executors.newFixedThreadPool(1);

        Runnable task = () -> {
            try {
                //Loop to read your services's output
                Thread.sleep(1000);
                System.out.println("This is from Task");
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
        };
        threadPool.execute(task);
        //Wait for the task to finish and shutdow the pool
        threadPool.shutdown();
    }
}

答案 2 :(得分:-1)

你有很多选择,其中一些是:

  • 简单线程
  • 的TimerTask
  • ScheduledExecutorService的

简单线程:

public class Task {
  public static void main(String[] args) {
      final long timeInterval = 1000;
      Runnable runnable = new Runnable() {
       public void run() {
          while (true) {
              System.out.println("Running Task ...");
                try {
                   Thread.sleep(timeInterval);
                } catch (InterruptedException e) {
                   e.printStackTrace();
                }
          }
       }
      };
      Thread thread = new Thread(runnable);
      thread.start();
  }
 }

的TimerTask:

 import java.util.Timer;
 import java.util.TimerTask;
 public class Task {
     public static void main(String[] args) {
          TimerTask task = new TimerTask() {
               @Override
               public void run() {
                   System.out.println("Running Task ...");
               }
          };
          Timer timer = new Timer();
          long delay = 0;
          long intevalPeriod = 1000; 
          timer.scheduleAtFixedRate(task, delay,intevalPeriod);
      } 
 }

ScheduledExecutorService的:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
             public void run() {
               System.out.println("Running Task ...");
             }
        };
    ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
    }
 }

答案 3 :(得分:-2)

这是一种维护主要java实例运行的方法,直到你想要退出。使用GUI执行此操作:

public static void main(String[] args){
    JFrame jFrame = new JFrame();
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setLocationRelativeTo(null);
    jFrame.setSize(480, 260);
    jFrame.setVisible(true);
    //do some task here
}