
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Killing threads in Java
Example
public class Main{ static volatile boolean exit = false; public static void main(String[] args){ System.out.println("Starting the main thread"); new Thread(){ public void run(){ System.out.println("Starting the inner thread"); while (!exit){ } System.out.println("Exiting the inner thread"); } }.start(); try{ Thread.sleep(100); } catch (InterruptedException e){ System.out.println("Exception caught :" + e); } exit = true; System.out.println("Exiting main thread"); } }
Output
Starting the main thread Starting the inner thread Exiting main thread Exiting the inner thread
The main class creates a new thread, and calls the ‘run’ function on it. Here, a Boolean value is defined, named ‘exit’, that is set to false initially. Outside a while loop, the ‘start’ function is called. In the try block, the newly created thread sleeps for a specific amount of time after which the exception would be caught, and relevant message would be displayed on the screen. After this, the main thread will be exited since the value of exit will be set to ‘true’.
- Related Articles
- Joining Threads in Java
- Difference Between Daemon Threads and User Threads In Java
- Minimum and Maximum Priority Threads in Java
- Killing Enemy in JavaScript
- How do threads communicate with each other in Java?
- Threads in C#
- User-level threads and Kernel-level threads
- Which method must be implemented by all threads in Java?
- On Killing a Tree
- Synchronizing Threads in Python
- Using Threads in Rust Programming
- Threads vs Processes in Linux
- Is GST killing some small businesses?
- Threads and Thread Synchronization in C#
- How to destroy threads in C#?

Advertisements