![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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