As we discussed earlier that we can create a thread by following two ways.
- By implementing Runnable interface.
- By extending Thread class.
Which is a better way to create a thread in java
- By implementing Runnable interface is a better way to create a thread in java because when we create a thread by extending Thread class, all Thread class methods are inherited while we can perform the task with the one method (run method) only. It results into overhead inheritance.
- Other reason is that java does not support multiple inheritance in case of classes. So if we create a thread by extending the Thread class, we will not be able to extend any other class.
1. Create thread example by implementing Runnable interface:
To create a thread using Runnable interface, create a class which implements Runnable interface. Runnable interface have only one method run().
Syntax:
public void run()
run() method will contain the code for created thread.
Now create a thread class object explicitly because our class is not extending thread class and hence its object can’t be treated as thread object. Pass class object that implements Runnable interface into thread class constructor to execute run method.
Example:
CreateThreadExample1.java
/** * This program is used to create thread using Runnable interface. * @author w3spoint */ class Test implements Runnable{ public void run(){ System.out.println("thread started."); } } public class CreateThreadExample2 { public static void main(String args[]){ //creating Test object. Test obj = new Test(); //creating thread Thread thrd = new Thread(obj); //start the thread. thrd.start(); } } |
Output:
thread started. |
2. Create thread example by extending Thread class:
Thread class provides methods to perform operations on threads.
Thread class is in Java.lang package.
Syntax:
public class Thread extends Object implements Runnable
Commonly used constructors of Thread class:
1. Thread().
2. Thread(Runnable target).
target – the class object whose run method is invoked when this thread is started. If null, this thread’s run method is invoked.
3. Thread(String name).
name – the name of the new thread.
4. Thread(Runnable target, String name).
target – the class object whose run method is invoked when this thread is started. If null, this thread’s run method is invoked.
name – the name of the new thread.
Example:
/** * This program is used to create thread using Thread class. * @author w3spoint */ class Test extends Thread{ public void run(){ System.out.println("thread started."); } } public class CreateThreadExample1 { public static void main(String args[]){ //creating thread. Test thrd1 = new Test(); //start the thread. thrd1.start(); } } |
Output:
thread started. |