简体   繁体   English

如何在Java中同步Thread.sleep和Thread.interrupt?

[英]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 . 我想编写一个在执行可中断调用(例如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 . 我想同步两个线程:一个线程调用Thread.sleep ,另一个线程等待直到第一个线程开始休眠并用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. 您无法确定,因为例如操作系统可能决定在Thread.sleep语句之前暂停第一个线程。 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? 为什么要在调用Thread.sleep之后中断? 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(). 进行中断以使它的效果与调用时间无关,无论它是在调用sleep()之前还是之后。 Do you want just test it? 您只想测试一下吗? then poll in a loop until the thread gets in TIMED_WAITING state: 然后循环轮询,直到线程进入TIMED_WAITING状态:

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 为了确保2个线程互相启动,您需要使用

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 我没有测试代码,但是这里是更多信息的文档: https : //docs.oracle.com/javase/tutorial/essential/concurrency/join.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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