杀死被阻止的帖子

时间:2018-05-14 12:57:09

标签: java multithreading concurrency

有没有办法打断阻塞线程?

例如,在下面的示例中,线程t2将被阻止,但是当线程被阻塞时,中断调用不会终止/中断线程,但是当它进入sleep方法时。

public class Main implements  Runnable{
    static Object MUTEX = new Object();
    public static void main(String[] args) throws Exception{
        Thread t1 = new Thread(new Main());
        Thread t2 = new Thread(new Main());
        System.out.println(t1.getId());
        System.out.println(t2.getId());
        t1.start();
        Thread.sleep(1000);
        t2.start();
        t2.interrupt();
        System.out.println("done main thread");


    }
    @Override
    public void run(){

        synchronized (MUTEX){
            try {

                System.out.println(Thread.currentThread().getId());
                Thread.sleep(1000 * 10);
            }
            catch (InterruptedException ix){
                System.out.println("Interrupt exception for:"+Thread.currentThread().getId());
                return;
            }
            System.out.println("done" + Thread.currentThread().getId());
        }
    }
}

0 个答案:

没有答案