0

In C, there is interrupt handler so the programmer can write a specific function for an interrupt. Is there any similar functionality in java? I have to interrupt thread and want to make it do something when interrupted.

백종빈
  • 143
  • 1
  • 11

2 Answers2

0

Java is higher-level programming language than C. You can deal with threads for example(not good practice, but only to show abstraction level)

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

Maybe try to deal with interruption handlers on OS level.

dgebert
  • 1,235
  • 1
  • 13
  • 30
0

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.

You can do a timed wait on a condition (wait/notify) instead of a simple sleep.

Example:

    /**
     * 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();
        }
    }
rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Oh! thank you very much wait is more good choice than sleep, because notify won't kill thread. Thanks a lot. – 백종빈 Sep 16 '17 at 09:09