是否对对象的休眠线程释放锁中断异常

时间:2016-11-05 17:11:19

标签: java multithreading thread-sleep

当线程处于休眠状态时,它仍然保持对象的锁定,当它被中断时,它是否释放锁定并进入就绪状态还是会继续执行而不改变状态?

1 个答案:

答案 0 :(得分:2)

  

当它被中断时,它是否释放锁并进入就绪状态   还是会在不改变状态的情况下继续执行?

线程被中断只是状态更改(已设置的标志)而不是状态更改,并且它对是否将释放锁定没有影响。

持有对象监视器的线程只有在相应的对象实例上调用wait(有或没有超时)或者它将从同步块中退出时才会释放它,被中断或不被更改这个规则的任何事情。

这是一个显示想法的简单代码:

// Used to make sure that thread t holds the lock before t2
CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(
    () -> {
        synchronized (someObject) {
            // Release t2
            latch.countDown();
            for (int i = 1; i <= 2; i++) {
                try {
                    System.out.println("Sleeping " + i);
                    // Sleep 2 sec and keep holding the lock
                    Thread.sleep(2_000L);
                    System.out.println("Sleep over " + i);
                } catch (InterruptedException e) {
                    System.out.println("Interrupted " + i);
                }
            }
        }
    }
);
Thread t2 = new Thread(
    () -> {
        try {
            // Wait to be release by t
            latch.await();
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        System.out.println("Trying to get in");
        synchronized (someObject) {
            System.out.println("In");
        }
    }
);
// Start the threads
t.start();
t2.start();
// Waiting 1 sec (< 2 sec) only before interrupting t
Thread.sleep(1_000L);
// Interrupt t
t.interrupt();

<强>输出:

Trying to get in
Sleeping 1
Interrupted 1
Sleeping 2
Sleep over 2
In

正如您在输出线程中看到的那样t2仅在线程t从同步块退出时才进入同步块(获取锁定)。线程t被中断的事实并未使其解除锁定。

相关问题