Java作为服务运行并停止jvm

时间:2018-07-16 04:28:31

标签: java multithreading concurrency

我有两个线程的Java程序。一种是运行主要功能,另一种是停止JVM /程序。

public class RunTest {


    private static final String EXIT = "exit";
    private CountDownLatch _shutdownSignal = new CountDownLatch(1);
    private static RunTest _instance;

    private void doRun() {

        System.out.println("Started continous run...");

        Thread exitListener = new Thread() {
            public void run() {
                BufferedReader stdin = null;
                try {

                    stdin = new BufferedReader(new java.io.InputStreamReader(System.in));
                    boolean doLoop = true;
                    while (doLoop) {
                        String line = stdin.readLine();

                        if (EXIT.equalsIgnoreCase(line)) {
                            doLoop = false;
                            System.out.println("Exit loop...");

                        }
                    }
                } catch (IOException ioex) {

                } finally {
                    signalShutdown();
                }
            }
        };

        try {
            // wait until new thread
            exitListener.setDaemon(true);
            exitListener.start();

            _shutdownSignal.await();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }

    }


    public static void main(String[] args) {
        try {
            _instance = new RunTest();
            _instance.doRun();

        } catch(Throwable ex) {
            System.out.println("Error occurred: " + ex.getMessage());
        }

    }

    public void signalShutdown() {
        _shutdownSignal.countDown();
    }
}

我可以通过键入“退出”来停止程序。 我想使用诸如start.sh

之类的东西作为服务运行该程序

但是,如果程序/ JM正在运行,那么如何使用stop.sh文件停止该程序。 ? (我认为我需要向标准输出发送“退出”到JVM)

有什么办法可以做。 ?

0 个答案:

没有答案