
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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’.
Advertisements