 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Use boolean value to stop a thread in Java
A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called.
A thread can be stopped using a boolean value in Java. The thread runs while the boolean value stop is false and it stops running when the boolean value stop becomes true.
A program that demonstrates this is given as follows:
Example
class ThreadDemo extends Thread {    public boolean stop = false;    int i = 1;    public void run() {       while (!stop) {          try {             sleep(10000);          } catch (InterruptedException e) {          }          System.out.println(i);          i++;       }    } } public class Demo {    public static void main(String[] args) {       ThreadDemo t = new ThreadDemo();       t.start();       try {          Thread.sleep(10000);       } catch (InterruptedException e) {       }       t.stop = true;       System.out.println("The thread is stopped");    } }  Output
1 2 3 4 5 The thread is stopped
Advertisements
 