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

时间:2014-07-17 04:18:33

标签: java multithreading synchronization

我有一个带有同步方法的Object:

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

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

我尝试拨打Thread.interrupt()Foo.notify(),但没有工作。

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

2 个答案:

答案 0 :(得分:4)

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

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 这个目的。来自Java doc of lockInterruptibly方法

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

答案 1 :(得分:0)

您必须设计线程以正确响应中断。除非线程正在检查一个,否则在调用interrupt()时它不会执行任何操作。这里有一个很好的解释:

http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html