可停止的Java控制台进度条

时间:2017-05-15 07:59:03

标签: java console progress-bar interruption

我正在寻找一种方法来阻止以下栏的进展:

private static void cancellaaaaaaaaable() throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    System.out.print(ANSI_RED);
    for(int i = 0; i < 79; i++){
        // Something that allows user input/interaction capable to stop the progressbar
        System.out.print("█");
        TimeUnit.MILLISECONDS.sleep(500);
    }
    System.out.print(ANSI_RESET);
}

当进度条启动时,用户应该有大约40秒的时间来决定停止并取消进度条。

enter image description here

有办法吗?任何键盘输入都很棒,除了那些粗暴地停止这个过程的人。

2 个答案:

答案 0 :(得分:3)

这是一个灵感来自how to read from standard input non-blocking?

的解决方案

我们的想法是检查是否有来自System.in的内容。

请注意,这仅在验证输入时有效(例如 Enter 键),但即使是空输入也可以( Enter 键直接按下),所以你可以添加一些&#34;按Enter取消&#34;消息。

private static void cancellaaaaaaaaable() throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    System.out.print(ANSI_RED);

    InputStreamReader inStream = new InputStreamReader(System.in);
    BufferedReader bufferedReader = new BufferedReader(inStream);
    for (int i = 0; i < 79; i++) {

        System.out.print("█");
        TimeUnit.MILLISECONDS.sleep(500);

        // Something that allows user input/interaction capable to stop the progressbar
        try {
            if (bufferedReader.ready()) {
                break;
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
    System.out.print(ANSI_RESET);
}

请注意,您可以使用Java Curses Library执行更高级的控制台操作。

答案 1 :(得分:1)

定义一个Callable:

 public Future<?> submit(Runnable task) {
       if (task == null) throw new NullPointerException();
       RunnableFuture<Object> ftask = newTaskFor(task, null);
       execute(ftask);
        return ftask;
   }

然后是FutureTask和ExecutroService:

class MyCallable implements Callable<Boolean> {

    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i <= 99; i++) {
            System.out.print("█");
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.getStackTrace();
                return false;
            }
        }
        return true;
    }
}

并在需要时取消:

public static void main(String[] args) throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    MyCallable callable1 = new MyCallable();
    FutureTask<Boolean> futureTask1 = new FutureTask<>(callable1);

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(futureTask1);
    TimeUnit.MILLISECONDS.sleep(500);
    futureTask1.cancel(true);
    System.out.println("\nDone");

}