The destroy()
method is used to stop the execution of thread groups and subgroups after the completion of the run()
method, which executes without any cleanup. It can also cause deadlock during thread execution similar to suspend()
. Previously in java 2.0, resume()
and suspend()
were used, but they caused system failure during execution.
As part of Java 11, Oracle removed stop()
and destroy()
methods from the java.lang.Thread
class. The reason being that these methods were considered unsafe. In current versions of java, we can stop or suspend a thread by using the Thread.interrupt()
method or a boolean flag
.
Since the release of java 11,
destroy()
is deprecated in the latest java versions.
void destroy()
It does not take any argument values.
It is a void method, meaning it does not return anything.
As highlighted, we are destroying currently running threads by using the destroy()
method from the Thread class.
import java.lang.*;public class Educative {public static void main(String[] args) {Thread thread = Thread.currentThread();thread.setName("Main Thread");// printing the recent threadSystem.out.println("All Recent Threads = " + thread);int cnt = Thread.activeCount();System.out.println("recently active threads = " + cnt);Thread thr[] = new Thread[cnt];// returning the number of threads that are copied into the specified arrayThread.enumerate(thr);// destroy main threadthread.destroy();// printing active threadsfor (int i = 0; i < cnt; i++) {// destroying child threadsthr[i].destroy();}}}