java - 是否中断 sleep 线程释放对象上的锁的异常

标签 java multithreading thread-sleep

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

最佳答案

When it is interrupted, does it release the lock and go to ready state or will it continue the execution without changing the state?

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

持有对象监视器的线程只有在相应对象实例上调用wait(有或没有超时)时才会释放它,或者当它从同步块(synchronized block)中退出时,无论是否被中断,都不会释放它。不要更改此规则的任何内容。


这是一个简单的代码,展示了这个想法:

// 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

正如您在输出中看到的那样,只有当线程 t 从同步块(synchronized block)退出时,线程 t2 才会进入同步块(synchronized block)(获取锁)。线程t被中断的事实并没有使它释放锁。

关于java - 是否中断 sleep 线程释放对象上的锁的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40441008/

相关文章:

java - 获取要加载的类所需的类列表

python - 在python中生成一个包含套接字连接的QThread

Python 线程化子函数

java - 我如何在 5 秒内运行代码然后跳转到 Android studio Java 中的其他代码?

java - 具有容器安全性的 Spring Boot

java - 我如何找出调用类?

python - 并行化Python列表理解并没有提高性能

java - 如何将 while 循环与 onTouch 函数一起使用? (安卓)

java - android - sleep ()然后绘制

java - 将此 if-then-else 语句替换为单个 return 语句