
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Questions & Answers
- How can we stop a thread in Java?
- Java Program to convert boolean value to Boolean
- Create a Boolean object from Boolean value in Java
- How to stop AsyncTask thread in android?
- How to stop asynctask thread in Kotlin?
- How to use a Boolean in JavaScript Constructors?
- How to convert a boolean value to string value in JavaScript?
- How to use isAlive() method of Thread class in Java?
- Convert a specified value to an equivalent Boolean value in C#
- How a thread can interrupt another thread in Java?
- Naming a thread in Java
- Convert Java Boolean Primitive to Boolean object
- How to convert a value into Boolean in JavaScript?
- How to create a thread in Java
- Updating boolean value in MySQL?
Advertisements