Create a Thread
To create a thread by instantiating an object of Thread.
There are two different ways to create a thread:
- By extending Thread class
- By implementing the Runnable interface.
By implementing the Runnable interface
The simplest way to create a thread is to create a class which implements the Runnable interface.
Step 1
The Runnable interface provides the run() method which you need to implement.
You should implement your complete business logic inside this run() method.
public void run()
Step 2
When you create a class that implements Runnable then You should instantiate thread object within that class.
Thread(Runnable threadObj, String threadName);
Hence, threadObj is an instance of a class that implements the Runnable interface and threadName provided to the new thread.
void start();
Example
By implementing the Runnable interface
public class ThreadRunnable implements Runnable{
public void run(){
System.out.println("Running...");
}
public static void main(String args[]){
ThreadRunnable tr=new ThreadRunnable();
Thread t =new Thread(tr);
t.start();
}
}
By extending Thread class
If you want to create a thread, you should create a new class that extends Thread class.
You will need to override run( ) method available in Thread class, which is the entry point for the thread.
You should implement your complete business logic inside this run() method.
It should call the start( ) method to start execution of the new thread.
Example
By extending Thread class
public class Threadextends extends Thread{
public void run(){
System.out.println("Running...");
}
public static void main(String args[]){
Threadextends tr=new Threadextends();
tr.start();
}
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com