Java Thread : stop() method


 

Java Thread : stop() method

In this section we are going to describe stop() method with example in java thread.

In this section we are going to describe stop() method with example in java thread.

Java Thread : stop() method

In this section we are going to describe stop() method with example in java thread.

stop() method :

Java thread provides method stop to stop any running thread. It is deprecated  as it causes exceptions. The main problem of using stop() method is that it cause damaged state of object as when you call Thread.stop() method, it may suddenly stop the execution of thread.

public final void stop() - This method forces the thread to stop execution of running thread.
It throws SecurityException if the current thread cannot modify the thread.

Example :

public class ThreadStop implements Runnable {

	public void run() {
		System.out.println("Starting " + Thread.currentThread().getName()
				+ "....");
		try {
			Thread.sleep(100);
		} catch (Exception e) {
		}
		System.out.println(Thread.currentThread().getName()
				+ " execution completed.");
	}

	public static void main(String[] args) throws Exception {
		Thread thread1 = new Thread(new ThreadStop());
		Thread thread2 = new Thread(new ThreadStop());

		thread1.start();
		thread2.start();
		// stop thread thread1
		thread1.stop();
		System.out.println(thread1.getName() + " stopped by user.");

		thread1.join();
		thread2.join();
	}
}

Output :

Thread-0 stopped by user.
Starting Thread-1....
Thread-1 execution completed.

Ads