Developer can create the thread in two ways as follows.
- By Extending Thread class
- By Implementing the Runnable interface
By extending Thread class
Java Multithreading, Following is an example to create a Thread by extending Thread class.
creatingthread.java
[java]class creatingthread extends Thread{
public void run(){
System.out.println("Hello, Thread is running...");
}
public static void main(String args[]){
creatingthread splesson=new creatingthread();
splesson.start();
}
} [/java]
Where developer provided method called public void run(), this needs to be used.
[java]public void run(){
System.out.println("Hello, Thread is running...");
} [/java]
To start the thread developer has to use start().
[java]splesson.start(); [/java]
Output
When compile the code following is the result will be displayed.
[java]Hello, Thread is running...[/java]
By implementing the Runnable interface
Following is an example to create a Thread by implementing the Runnable
inerface .
creatingthread.java
[java]class creatingthread implements Runnable{
public void run(){
System.out.println("Hello, thread is running...");
}
public static void main(String args[]){
creatingthread m1=new creatingthread();
Thread t1 =new Thread(m1);
t1.start();
}
} [/java]
Java Multithreading, The difference between
extends Thread and
implements Runnable is that once if the developer declare the extends then there will be no scope to extend other classes, but it is possible in Runnable interface.
Output
When compile the code following is the result will be generated.
[java]Hello, thread is running...[/java]
Difference between implements Runnable and extends Thread
Java supports single inheritance so user can only extend single class.
Using the Runnable instance to encapsulate the code which should run in parallel provides better reusability. User can pass that Runnable to any other thread or thread pool.
When user extends Thread class, after that user can’t extend any other class which required.
When user extends Thread class, each of thread creates unique object and associate with it.
When user implements Runnable, it shares the same object to multiple threads.