简体   繁体   中英

How to synchronize Thread.sleep and Thread.interrupt in Java?

I would like to write a test to interrupt a thread when it is executing an interruptible call, eg 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 ?

You can't know for sure, since for example the OS could decide to suspend the first thread right before the Thread.sleep statement. In practice, if you can use a small sleep in the second thread too as well as synchronization and it should be fine:

final CountdownLatch start = new CountdownLatch(1);

final Thread t1 = new Thread (new Runnable () {
    public void run() {
        start.await();
        Thread.sleep(1000);
    }
});

Thread t2 = new Thread (new Runnable () {
    public void run() {
        start.await();
        Thread.sleep(100); //wait a little to make sure that t1 is asleep
        t1.interrupt();
    }
});

t1.start();
t2.start();

Thread.sleep(100); //wait to make sure both threads are started
start.countdown();

Use a synchronizer and notify the interrupter thread on its lock before sleeping from the sleeper thread. Introduce a very small delay (far less than the sleep time of sleeper thread) and after wakeup issue an interrupt on the sleeper thread.

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();

to guarantee that 2 threads start after each other, you will need to use

join() 

for example (ignoring handling the exceptions) :

Thread t1 = new Thread();
Thread t2 = new Thread();

t1.start();
t2.join();
t2.start();

i didnt test the code, but here is the documentation for more information : https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM