用于java线程的事件监听的回调方法?

用于java线程的事件监听的回调方法?

我在自定义 Thread 类中 Override 了 destroy() 方法,但是在此线程结束时并未被调用,我想要的是类似 onDestroy() 的方法,使我可以设置当此线程结束、被终止(中止)、被销毁时需要执行的内容。如果原生的线程未提供此种回调方法,是否有第三方加强版 Thread 是提供了此方法的?

线程结束不会调用调用destroy() 方法。最好再主动调用一下

参考

img

public class JavaDestroyExp extends Thread 
{
    JavaDestroyExp(String threadname, ThreadGroup tg)
    {
        super(tg, threadname);
        start();
    }
    public void run()
    {
        for (int i = 0; i < 2; i++) 
        {
            try
            {
                Thread.sleep(10);
            }
            catch (InterruptedException ex) {
                System.out.println("Exception encounterted");}
        }
        System.out.println(Thread.currentThread().getName() +
              " finished executing");
    }
    public static void main(String arg[]) throws InterruptedException, SecurityException
    {
        // creating a ThreadGroup
        ThreadGroup g1 = new ThreadGroup("Parent thread");
        // creating a child ThreadGroup for parent ThreadGroup
        ThreadGroup g2 = new ThreadGroup(g1, "child thread");
        
        // creating a thread 
        JavaDestroyExp t1 = new JavaDestroyExp("Thread-1", g1);
        // creating another thread 
        JavaDestroyExp t2 = new JavaDestroyExp("Thread-2", g1);
        
        // block until other thread is finished
        t1.join();
        t2.join();
 
        // destroying child thread
        g2.destroy();
        System.out.println(g2.getName() + " destroyed");
        
        // destroying parent thread
        g1.destroy();
        System.out.println(g1.getName() + " destroyed");
    }
}