2017-06-16 70 views
-1

我开发一个Java独立的应用程序,其中有上传批处理文件来REST API。我希望在需要从命令提示符下停止应用程序,但如果应用程序正在上传文件,则必须完成该操作,并且必须在开始上传另一个文件之前停止该应用程序。如何停止从命令提示符下的Java应用程序正常

+1

我建议做对非守护线程,以及如何在JVM退出一些研究。 https://stackoverflow.com/questions/2213340/what-is-daemon-thread-in-java – Steve

回答

0

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

https://stackoverflow.com/a/17792988/2884613

+0

谢谢你回答raychz。我用了两个标志。以下是我用过的示例代码。 – jaswanth

1

它不能阻止你希望的任何时间,因为(我认为)你的程序在单个线程中运行,因此必须完成的顺序每个任务它被赋予。

当上传文件的列表,你可以提供一些听众的在前面的一个线程,同时上传文件的背景。当Thread1收到它需要退出的信息时,它可以设置某种全局布尔值,它在线程2开始上传第二个文件之前进行检查。

制作上传过程在后台线程可以让你在这个过程中修改程序。

如果你对一般优雅地退出程序寻找文件,它可以在这里找到:http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exit%28int%29

+0

感谢您的回答。我使用shutdown hook实现,并使用全局布尔值,就像你说的那样。 – jaswanth

0

公共类主要{

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继承Thread {

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。

相关问题