开发者

Java console program and CTRL-C

import java.util.Scanner;

public class test {
    public static void main(String[] args) {

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("Shutdown.");
            }
        });

        String input ="";
        Scanner in = new Scanner(System.in);

        while(true) {
            System.out.print("> ");
//          if (in.hasNext())
                input = in.nextLine();

            if (input.equalsIgnoreCase(""))
                continue;
        }
    }
}

I have this simple console program and I'm trying to implement Ctrl-C 开发者_JS百科to simply quit. After a search I've had partial success using a shut down hook, however it's not working cleanly.

With the line commented the program seems to loop a number of times before quitting (is this the main thread just looping itself?) and with the comment I get an exception on the next line's attempt to read the input stream.

What's the best way to acheive this?


you need to do do something to stop the loop. add private static volatile boolean running = true; to the class, change while(true) to while(running) then get the shutdown hook to set running=false; and check your results. Volatile will ensure your application still shuts down promptly when run under multiple proccessors and/or cores.

[EDIT]

The issue is that the Scanner is blocking (sorry I missed it the first time) which requires you to interrupt the main thread;

private static Thread mainThread;
public static void main(String[] args)
{
    mainThread = Thread.currentThread();

    Runtime.getRuntime().addShutdownHook(new Thread()
    {
        public void run()
        {
            Test.mainThread.interrupt();
        }
    });
    ... // etc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜