3

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

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 秒的时间来决定停止和取消进度条。

在此处输入图像描述

有没有办法做到这一点?任何键盘输入都很棒,除了那些残酷地停止该过程的键盘输入。

4

2 回答 2

3

这是一个灵感来自如何从标准输入非阻塞读取的解决方案?

这个想法是检查是否有东西可以读取System.in

请注意,这仅在输入经过验证(如使用Enter键)时才有效,但即使是空输入也有效(Enter直接按下键),因此您可以添加一些“按 Enter 取消”消息。

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执行更高级的控制台操作。

于 2017-05-15T08:13:15.990 回答
1

定义一个可调用的:

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;
    }
}

然后是 FutureTask 和 ExecutroService:

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");

}

并在您需要时取消它:

futureTask1.cancel(true);
于 2017-05-15T08:27:44.490 回答