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.
Asked
Active
Viewed 1,240 times
0
-
[maybe search SO before you post](https://stackoverflow.com/questions/1229763/how-to-let-java-handle-system-interrupts-like-ctrlc) – Hans Petter Taugbøl Kragset Sep 15 '17 at 11:41
-
1interrupt handler is a function of the os, not of the language. – Erik Sep 15 '17 at 11:42
-
In C there is no interrupt handler. Your question makes no sense, also this is in no way related to C, so why tag it? – Antti Haapala -- Слава Україні Sep 15 '17 at 11:58
-
Interrupt handler written in C on Unix. So I added tag C – 백종빈 Sep 15 '17 at 12:02
-
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. – 백종빈 Sep 15 '17 at 12:30
2 Answers
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
-
How's that a distinction when C actually **does have threads**? – Antti Haapala -- Слава Україні Sep 15 '17 at 11:59
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