• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

stopping a thread using volatile boolean flag

How to stop a thread?

May 31, 2017 By j2eereference Leave a Comment

How to stop a thread?

In multithreading, we start a thread using start () method and we execute thread using run() method .Similarly we also have wait(),notify and sleep() method to let thread wait or sleep for sometime. But it is difficult to stop a thread as stop() method has been deprecated. So,we need to apply some logic to stop the thread . There can be many ways to stop a thread but in this tutorial we will use Boolean flag variable to stop a thread.

Why stop() method is deprecated in java:

When we stop a thread using Thread.stop() method it causes the thread to release all the acquired monitors and throw ThreadDeath error and cauese. If any of the objects previously locked by these monitors were in an inconsistent state, then it becomes visible to other threads, which may lead the program to some unexpected  behavior.

Program to stop a thread

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class ThreadDemo extends Thread
{
    private volatile boolean stopFlag = true;
    public void stopThread()
    {
     stopFlag = false;
    }
    
    @Override
    public void run()
    {
        while (stopFlag)
        {
            System.out.println(Thread.currentThread().getName()+" is running");
        }
        
        System.out.println(Thread.currentThread().getName()+" has stopped running");
    }
}
public class ThreadStopDemo
{  
    public static void main(String[] args)
    {
     ThreadDemo threadDemo = new ThreadDemo();
        threadDemo.start();
        
   try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        
        threadDemo.stopThread();
    }    
}

OutPut:

In above example, we declare one boolean volatile variable stopFlag in a thread. Set this flag value as true. Inside run() method use while loop by passing stopFlag .If flag value is true then keep the task performed in while loop and thread will continue to run until flag becomes false. We have defined stopThread() method which is called from main method after thread start .This method will set the stopFlag as false and stops the thread. Also note that we have declared flag as volatile. Every Thread has its own local memory so it is good practice to make stopFlag as volatile because value of stopFlag can be alter from any thread if not declared volatile and making it volatile guarantees that thread will always read updated value of stopFlag.

Related Posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof

Filed Under: Core Java Tagged With: How to stop a thread, stopping a thread using volatile boolean flag

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.