How to stop uninterruptible threads in Java

后端 未结 6 1969
有刺的猬
有刺的猬 2020-12-06 14:52

I have a Java application that I CAN\'T EDIT that starts a java.lang.Thread that has this run() method:

p         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 15:47

    Ok, I've found the solution and it's really really simple, just sleep the thread and then interrupt it!

    final Thread t = getTheThreadToClose();
    
    //Final is important because only in this way you can pass it to the following new Thread
    
    if (t != null && t.isAlive() && !t.isInterrupted()){
        try{
           new Thread(){
               public void run(){
                   try{ 
                      t.sleep(3000);//SLEEP INSIDE THE NEW THREAD
                   }
                   catch(InterruptedException ex){}
               }
           }.start();
    
           t.interrupt();//INTERRUPT OUTSIDE THE NEW STARTED THREAD
        }
        catch(Exception e){}
    }
    

    It works in all cases!

    I wanna thank you all for your really useful help, especially venomrld and Toby that gave me inspiration for the solution with their words ;-), and this wonderfoul site that let me ALWAYS solve all my programming problems.

    Thank you all again and Happy New Year!

提交回复
热议问题