java中是否有中断处理程序?

Is there interrupt handler in java?

在C语言中,有中断处理程序,因此程序员可以为中断编写特定的函数。 java有没有类似的功能?我必须中断线程并想让它在中断时做一些事情。

Java 是比 C 更高级的编程语言。你可以处理例如线程(不是很好的做法,但只是为了显示抽象级别)

if (Thread.interrupted()) {
        // Something to do
        return;
    }

也许尝试在 OS 级别处理中断处理程序。

One thread set the text to the label that is subtitle. I use 'sleep' function for syncing the subtitle and video. So if people want to change the speed of setting subtitle, they press the button. Then the thread interrupted and perform changing the sleep time. And restart setting subtitle using changed time for sleep.

您可以根据条件 (wait/notify) 进行定时等待,而不是简单的休眠。

示例:

    /**
     * Worker thread interrupt condition object.
     */
    final AtomicBoolean interruptCond = new AtomicBoolean();

    /**
     * Sleeps for a given period or until the interruptCond is set
     */
    public boolean conditionalSleep(long ms) throws InterruptedException {
        long endTime = System.currentTimeMillis() + ms, toGo;
        while ((toGo = endTime - System.currentTimeMillis()) > 0) {
            synchronized (interruptCond) {
                interruptCond.wait(toGo);
                if (interruptCond.get())
                    break;
            }
        }
        return interruptCond.get();
    }

    /**
     * The worker thread loop.
     */
    public void run() {
        while (true) {
            if (conditionalSleep(timeToNextSubtitle)) {
                adjustSpeed();
                continue;
            }
            showNextSubtitle();
        }
    }

    /**
     * Interrupts the worker thread after changing timeToNextSubtitle.
     */
    public void notifyCond() {
        synchronized (interruptCond) {
            interruptCond.set(true);
            interruptCond.notifyAll();
        }
    }