- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Controlling the main thread in Java
A thread can be created by implementing the Runnable interface and overriding the run() method.
The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread. Also, it is the last thread to finish execution as various shut-down actions are performed by it.
A program that demonstrates this is given as follows:
Example
public class Demo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Main thread: " + t); t.setName("current"); System.out.println("Current thread: " + t); try { for (int i = 1; i <= 5; i++) { System.out.println(i); Thread.sleep(10); } } catch (InterruptedException e) { System.out.println("Main thread is interrupted"); } System.out.println("Exiting the Main thread"); } }
Output
Main thread: Thread[main,5,main] Current thread: Thread[current,5,main] 1 2 3 4 5 Exiting the Main thread
- Related Articles
- Main thread vs child thread in C#
- How to fix "Exception in thread main" in java?
- User Thread vs Daemon Thread in Java?
- Daemon thread in Java
- Thread Pools in Java
- How a thread can interrupt another thread in Java?
- What is the Thread class in Java?
- Inter thread communication in Java
- Get current thread in Java
- Demonstrate thread priorities in Java
- Change Thread Priority in Java
- Java Thread Priority in Multithreading
- Naming a thread in Java
- Thread Interference Error in Java
- Is Java matcher thread safe in Java?

Advertisements