如何正常地从命令提示符停止java应用程序

时间:2017-06-16 17:25:03

标签: java

我正在开发一个java独立应用程序,它必须将批量文件上传到其他api。我想在命令提示符处需要时停止应用程序,但如果应用程序正在上传文件,则必须完成该操作并且必须在开始上载另一个文件之前停止。

3 个答案:

答案 0 :(得分:1)

它无法随时停止,因为(我假设)您的程序在单个线程上运行,因此必须按照给定的顺序完成每个任务。

上传文件列表时,您可以在一个线程的前面提供某种类型的侦听器,同时在后台上传文件。当Thread1收到它需要退出的信息时,它可以设置线程2在开始上传第二个文件之前检查的某种全局布尔值。

使上传过程成为后台线程允许您修改过程中的程序。

如果您正在寻找有关正常退出该计划的文档,可以在此处找到:http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exit%28int%29

答案 1 :(得分:0)

您可以在应用程序的退出代码JVM关闭挂钩中快速检查isUploading标志。如果为false,则继续退出。如果为true,请等待上载过程完成或超时。

请参阅https://stackoverflow.com/a/17792988/2884613

答案 2 :(得分:0)

public class Main {

public static void main(String[] args) {

    Runtime r = Runtime.getRuntime();
    r.addShutdownHook(new ShutdownHook());

    while(Flag.flag){

        System.out.println("Application is still running......");


    }

    if(!Flag.flag) {
        System.out.println("goin to exit the application");
        Flag.shutdownFlag = false;
        return;
    }

}

}

公共类标志{

public static boolean flag = true;
public static boolean shutdownFlag = true;

}

公共类ShutdownHook扩展了线程{

public void run() {

    System.out.println("Shutdown hook is initiated");
    Flag.flag = false;

    while (Flag.shutdownFlag) {
        System.out.println("Waiting for application to complete the task..");
    }

}

}

我在命令提示符下运行jar。一旦我们想要停止应用程序,我们就可以在命令提示符下给出ctrl + c。