如何中断被阻止的同步方法

whi*_*fee 5 java multithreading synchronization

我有一个带有synchronized方法的Object:

public class Foo {
    public synchronized void bar() {
        // Do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

我有成千上万的线程调用相同的方法.当我想退出程序时,如何中断这些等待的线程以便程序立即退出?

我曾试图打电话Thread.interrupt()Foo.notify(),但不起作用.

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

ver*_*tas 6

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

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

为此,请使用java.util.concurrent.locks.Lock。从Java文档中的lockInterruptible方法

/**
     * 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.
Run Code Online (Sandbox Code Playgroud)

参考:http : //grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/locks/ReentrantLock.java#ReentrantLock.lockInterruptible%28%29