Way of creating thread:
- By implementing Runnable interface.
- By extending Thread class.
Important points:
- We discussed earlier that every thread has a job associated with it. This job is what we are performing in run method.
- By default every program have one main thread. It may have number of daemon threads. GC is a daemon thread. It is the responsibility of main thread to start the child threads.
1. 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 w3schools */ 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. 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 w3schools */ 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. |
Download this example.
Next Topic: Commonly used methods of Thread class.
Previous Topic: Thread life cycle in java.