- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
What are the ways in which a thread is created in Java?
There are two ways to create a new thread of execution.
By Implementing a Runnable Interface
One way to create a thread is by implementing the Runnable interface to do so −
- Create a class and implement the Runnable interface.
- Override the run() method of the Runnable interface.
- Instantiate the Thread class by passing the object of the current class (a class that implements the Runnable interface) to its constructor.
- Once a Thread object is created, you can start it by calling start() method, which in turn executes a call to run() method.
Example
class first implements Runnable { public void run(){ try { for(int i=0;i<=20;i+=2) { Thread.sleep(600); System.out.println(i); } } catch(Exception e) { } } class MyThreadd { public static void main(String args[]) { first obj = new first(); Thread thread = new Thread(obj); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); System.out.println(thread.isAlive()); } }
Output
true 0 2 4 6 8 10 12 14 16 18 20
- Related Articles
- What are all the ways an object can be created in Java?
- Which collection classes are thread-safe in Java?
- What is a daemon thread in Java?
- When a thread is created and started, what is its initial state?
- What is the Thread class in Java?
- How many ways a String object can be created in java?
- What are the different ways in which water gets contaminated?
- What are the different ways in which air gets polluted?
- What method is used to create a daemon thread in Java?
- Is Java matcher thread safe in Java?
- What are various ways to compare dates in Java?
- What are the 6 ways to use this keyword in Java?
- How a thread can interrupt another thread in Java?
- Naming a thread in Java
- Is Swing thread-safe in Java?

Advertisements