I would like to write a test to interrupt a thread when it is executing an interruptible call, e.g. Thread.sleep
.
I would like to synchronize two threads: one thread calls Thread.sleep
and another one waits till the first thread starts sleeping and interrupts it with Thread.interrupt
.
How can I make sure that the 2nd thread interrupts the 1st one after it starts sleeping ? Is it possible ?
Why do you want interrupt after Thread.sleep is invoked? The interrupt is made so that it's effect is the same regardless of its invocation time, was it before or after calling to sleep(). Do you want just test it? then poll in a loop until the thread gets in TIMED_WAITING state:
t1.start();
while (t1.getState()!= Thread.State.TIMED_WAITING) {
Thread.sleep(10);
}
t1.interrupt();