What is the thread destroy() method in java?

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.

Syntax


void destroy()

Parameters

It does not take any argument values.

Return Value

It is a void method, meaning it does not return anything.

Example

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 thread
System.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 array
Thread.enumerate(thr);
// destroy main thread
thread.destroy();
// printing active threads
for (int i = 0; i < cnt; i++) {
// destroying child threads
thr[i].destroy();
}
}
}

Free Resources