How to Kill a Thread in Java
A program that executes a single set of instructions is challenging enough for most beginning programmers. But as they move to more advanced projects they will begin needing to create multiple sets of actions that execute simultaneously. In programming terms, this is called "multi-threading," where each thread is a set of instructions for execution of a set of tasks. Java provides a number of built-in function for the creation and management of multiple threads. While explicitly killing a thread is poor programming form in Java, it is possible to do so with the "stop" method.
Instructions
-
-
1
Declare your thread using the line "Runnable r = new MyRunnableClass();" where "MyRunnableClass" is a java class that implements the "Runnable" interface. This gives the class access to the Java methods for regulating thread function.
-
2
Write the code to initiate the thread by typing "Thread t = new Thread(r);" followed by "t.start();" on the next line in your source code. This will initiate that class to begin running as an independent thread.
-
-
3
Type the code "t.stop();" in the part of your source code where you want to kill the thread.
-
1
Tips & Warnings
Killing a threat, just like killing a program while it is running, can have negative side effects. Killing threads in the testing and development phases of your program can serve useful purposes. But for finished programs it is safer, and better coding style, to suspend your threads and implement your own code to safely wrap up whatever resources the thread was using. Consult the link in the "Resources" section below for more information on suspending threads.
References
Resources
- Photo Credit Comstock/Comstock/Getty Images