InterviewSolution
Saved Bookmarks
| 1. |
Stop a Thread in Java |
|
Answer» Stopping a thread in Java can be a little complicated as there is no working stop method. This is quite DIFFERENT than starting a thread in Java as there is a start() method available. When Java was first released, there was a stop() method in Thread class, but that has since been deprecated. A program that demonstrates how to stop a thread in Java using a personal stop() method is given as FOLLOWS: import static java.lang.Thread.currentThread; import java.util.concurrent.TimeUnit; public class Demo { public static VOID main(String args[]) throws InterruptedException { Server ser = new Server(); Thread thread = new Thread(ser, "T1"); thread.start(); System.out.println(currentThread().getName() + " is stopping Server thread"); ser.stop(); TimeUnit.MILLISECONDS.sleep(200); System.out.println(currentThread().getName() + " is finished now"); } } class Server implements RUNNABLE { private volatile boolean exit = false; public void run() { while(!exit) { System.out.println("The Server is running"); } System.out.println("The Server is now stopped"); } public void stop() { exit = true; } }The OUTPUT of the above program is as follows: main is stopping Server thread The Server is running The Server is now stopped main is finished now |
|