gpt4 book ai didi

java - 如何中断被阻塞的同步方法

转载 作者:搜寻专家 更新时间:2023-10-31 20:02:17 25 4
gpt4 key购买 nike

我有一个带有同步方法的对象:

public class Foo {
public synchronized void bar() {
// Do stuff
}
}

我有数千个线程调用同一个方法。当我想退出程序时,如何打断这些等待的线程,使程序立即退出?

我尝试调用 Thread.interrupt()Foo.notify() 但没有成功。

问题是:阻塞同步方法是否可中断?

最佳答案

阻塞同步方法是否可中断? ,但下面是实现您想要做的事情的最佳方式!

public class Foo {
private final Lock lock = new ReentrantLock();
public void bar() throws InterruptedException {
lock.lockInterruptibly();
try {
// Do stuff
}finally {
lock.unlock()
}
}
}

请使用 java.util.concurrent.locks.Lock这个目的。来自 lockInterruptibly 方法的 Java 文档

/**
* Acquires the lock unless the current thread is
* {@linkplain Thread#interrupt interrupted}.
*
* <p>Acquires the lock if it is available and returns immediately.
*
* <p>If the lock is not available then the current thread becomes
* disabled for thread scheduling purposes and lies dormant until
* one of two things happens:
*
* <ul>
* <li>The lock is acquired by the current thread; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts} the
* current thread, and interruption of lock acquisition is supported.
* </ul>
*
* <p>If the current thread:
* <ul>
* <li>has its interrupted status set on entry to this method; or
* <li>is {@linkplain Thread#interrupt interrupted} while acquiring the
* lock, and interruption of lock acquisition is supported,
* </ul>
* then {@link InterruptedException} is thrown and the current thread's
* interrupted status is cleared.

引用:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/locks/ReentrantLock.java#ReentrantLock.lockInterruptibly%28%29

关于java - 如何中断被阻塞的同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24794812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com