This question already has answers here:
How can I “intercept” Ctrl+C in a CLI application?
                                
                                    (4个答案)
                                
                        
                4年前关闭。
            
        

我正在尝试运行一个看起来有“ 9条生命”的Java程序。运行时,它只是无限循环地打印出以下内容:

GlobalVar = 1
GlobalVar = 1
GlobalVar = 1
/* etc */
GlobalVar = 1
GlobalVar = 1


然后,一旦我们CTRL+C杀死了程序,而不是退出并转到命令提示符下,它应该像这样重新进行:

GlobalVar = 2
GlobalVar = 2
GlobalVar = 2


然后不停地打开GlobalVar设置为3、4、5等。

首先,我知道此代码有点不切实际-仅用于学术练习。但是我正在学习Java。

到目前为止,这是我的代码:

import java.io.*;
public class SHTest {

            static int globalVar = 0;

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

        System.out.println ("The Global Var is " + globalVar);
        Runtime.getRuntime ().addShutdownHook ( new Thread () {
            @Override
            public void run () {

            globalVar += 1;
 /* shutdown */
           String[] command = {"C://Program Files//Java//jdk1.7.0_02//bin//java.exe", "SHTest"};  //args[0] ... CreateTexts
           ProcessBuilder pb = new ProcessBuilder(command);
           pb.redirectErrorStream(true);

           try {
               Process exec = pb.start();
               BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));
               String text = null;
           while ((text = br.readLine()) != null) {
               System.out.println(text);
           }

           System.out.println("Process exited with " + exec.waitFor());
           }

            catch(IOException io) { }

            catch(InterruptedException inter) { }


            }
        } );  //end addShutdownHook()

        //int copyGlobalVar = globalVar;
        while ( true  ) {
            System.out.println ( "Looping " + globalVar );
            Thread.sleep ( 800 );
        }
    }


    }


参考:

Capture SIGINT in Java

Why can't I re-execute a Java program from within an Exception block?

addShutdownHook method

注意:我愿意使用Windows批处理文件,因为JVM在这些方面似乎有其自身的局限性。或其他工具。即使对于Linux OS,也可以

最佳答案

静态变量globalVar将在该过程的破坏和恢复中幸免。在新进程中,它将重新初始化为0。应将其作为参数传递给进程,然后应将globalVar初始化为该参数的值。

10-07 13:08