• Skip to primary navigation
  • Skip to 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

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

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID
  • What is exchanger in concurrency?

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

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

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

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

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.