0

Is there any way to interrupt blocking thread?

For example, in the following example the thread t2 would be blocked, however the interrupt call doesn't kill/interrupt the thread while it's blocked, but while it enters the sleep method.

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());
        }
    }
}
Aladdin
  • 1,207
  • 2
  • 16
  • 26
  • No there isn't (a way to kill a thread, interrupting a blocking thread is possible but not in the sense you assume), so make sure you're not writing code that would make you need to kill threads. – Kayaman May 14 '18 at 13:00
  • 1
    google doesn't hurt https://stackoverflow.com/questions/32024436/why-cant-thread-interrupt-interrupt-a-thread-trying-to-acquire-lock – Jan Ossowski May 14 '18 at 13:00

0 Answers0