Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we stop a thread in Java?
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method. The stop() method is deprecated in Java due to thread-safety issues.
Syntax
@Deprecated public final void stop()
Example
import static java.lang.Thread.currentThread;
public class ThreadStopTest {
public static void main(String args[]) throws InterruptedException {
UserThread userThread = new UserThread();
Thread thread = new Thread(userThread, "T1");
thread.start();
System.out.println(currentThread().getName() + " is stopping user thread");
userThread.stop();
Thread.sleep(2000);
System.out.println(currentThread().getName() + " is finished now");
}
}
class UserThread implements Runnable {
private volatile boolean exit = false;
public void run() {
while(!exit) {
System.out.println("The user thread is running");
}
System.out.println("The user thread is now stopped");
}
public void stop() {
exit = true;
}
}
Output
main is stopping user thread The user thread is running The user thread is now stopped main is finished now
Advertisements