【问题标题】:Returning/Stopping the execution of a function on a keypress in Java在Java中的按键上返回/停止执行函数
【发布时间】:2026-02-08 06:55:01
【问题描述】:

我的程序中有一个特定的功能,我想在按下一个键时停止。我为此目的设置了一个本机键盘挂钩。现在,当检测到该键时,我调用 System.exit(0)。但是,我不想退出程序,只需停止该操作并返回调用它的位置即可。下面给出一个例子。

public class Main {
    public static void main(String[] args) {
        System.out.println("Calling function that can be stopped with CTRL+C");
        foo(); // Should return when CTRL+C is pressed
        System.out.println("Function has returned");
    }
}

我尝试将 foo() 的调用放在一个线程中,这样我就可以调用 Thread.interrupt() 但我希望函数调用是阻塞的,而不是非阻塞的。 foo() 中也有阻塞 IO 调用,所以除非有必要,否则我宁愿不处理中断,因为我必须处理 ClosedByInterruptException 异常,而这之前已经引起了问题。

另外foo()的主体很长,里面有很多函数调用,所以不能在函数中写if (stop == true) return;

有没有比创建阻塞线程更好的方法来做到这一点?如果是这样,怎么做?如果没有,我将如何创建阻塞线程?

【问题讨论】:

  • 您的问题不清楚。您是否希望foo() 在按下某个键时立即返回,无论它当时在做什么?你说foo会阻塞I/O调用...如果foo在按键被按下时处于阻塞调用中,你希望它立即中断吗?
  • 不,我确实希望它立即被打断。当我提到这一点时,我正在考虑如何捕获另一个异常(ClosedByInterruptException),以及当我尝试它时如何搞砸了很多事情。但无论它在做什么,我都绝对希望它停止。我在帖子中澄清了这一点。
  • 在英语中,要么是“不,我想要...”要么是“是的,我愿意我> 想要……”。您的回复仍然模棱两可,请您澄清一下。
  • 我很抱歉。是的,无论如何我都希望立即中断执行。
  • 这很难做到正确,当foo 在 I/O 上被阻塞时,您可能无法涵盖所有​​情况。本质上,您必须在自己的线程上运行foo,在另一个线程上运行键盘监视器,然后在适当的时候中断foo。然后foo 必须检查键盘监视器在适当位置设置的标志并返回。

标签: java return control-flow program-flow


【解决方案1】:

这个怎么样?

// Create and start the thread
MyThread thread = new MyThread();
thread.start();

while (true) {
    // Do work

    // Pause the thread
    synchronized (thread) {
        thread.pleaseWait = true;
    }

    // Do work

    // Resume the thread
    synchronized (thread) {
        thread.pleaseWait = false;
        thread.notify();
    }

    // Do work
}

class MyThread extends Thread {
    boolean pleaseWait = false;

    // This method is called when the thread runs
    public void run() {
        while (true) {
            // Do work

            // Check if should wait
            synchronized (this) {
                while (pleaseWait) {
                    try {
                        wait();
                    } catch (Exception e) {
                    }
                }
            }

            // Do work
        }
    }
}

(取自http://www.exampledepot.com/egs/java.lang/PauseThread.html不是我自己的作品)

【讨论】: