
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to create a thread in Java
A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called.
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 and it is the last thread to finish execution.
A program that demonstrates this is given as follows:
Example
class ThreadDemo implements Runnable { Thread t; ThreadDemo() { t = new Thread(this, "Thread"); System.out.println("Child thread: " + t); t.start(); } public void run() { try { System.out.println("Child Thread"); Thread.sleep(50); } catch (InterruptedException e) { System.out.println("The child thread is interrupted."); } System.out.println("Exiting the child thread"); } } public class Demo { public static void main(String args[]) { new ThreadDemo(); try { System.out.println("Main Thread"); Thread.sleep(100); } catch (InterruptedException e) { System.out.println("The Main thread is interrupted"); } System.out.println("Exiting the Main thread"); } }
Output
Child thread: Thread[Thread,5,main] Main Thread Child Thread Exiting the child thread Exiting the Main thread
- Related Questions & Answers
- How to create a thread in JShell in Java 9?
- How to create a thread using lambda expressions in Java?
- How to create a thread using method reference in Java?
- How to create a thread in C#?
- How to create a thread in android?
- How to create a thread by using anonymous class in Java?
- How to create a thread without implementing the Runnable interface in Java?
- How a thread can interrupt another thread in Java?
- What method is used to create a daemon thread in Java?
- How to interrupt a running thread in Java?
- C# Program to create a Simple Thread
- C# Program to Create a Thread Pool
- How to make a class thread-safe in Java?
- How to make a collection thread safe in java?
- Naming a thread in Java
Advertisements