Thread
can be called as light weight process
. Java supports multithreading , so it allows your application to perform two or more task concurrently. Multithreading can be of advantage specially when now a days, machine has multiple CPUs, so multiple tasks can be executed concurrently.Thread can be created in two ways.
- By extending Thread class
- By implementing Runnable interface
By extending Thread class:
Create a class FirstThread.java as below.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog.thread; public class FirstThread extends Thread{ public void run() { System.out.println("Thread is running"); } } |
Create main class named ThreadExampleMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog.thread; public class ThreadExampleMain { public static void main(String args[]) { FirstThread ft= new FirstThread(); ft.start(); } } |
By implementing Runnable interface:
The other way is , you need to implement Runnable interface and override public void run() method. You need to instantiate the class, pass created object to Thread constructor and call start method on thread object to execute thread as different threads.
Create a class FirthThread.java as below.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog.thread; public class FirstThread implements Runnable{ public void run() { System.out.println("Thread is running"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog.thread; public class ThreadExampleMain { public static void main(String args[]) { FirstThread ft= new FirstThread(); Thread t=new Thread(ft); t.start(); } } |
Thread vs Runnable which is better?
- Java does not support multiple inheritance so if you extend Thread class and you can not extend any other class which is needed in most of the cases.
- Runnable interface represents a task and this can be executed with help of Thread class or Executors.
- When you use inheritance, it is because you want to extend some properties of parent, modify or improve class behavior. But if you are extending thread class just to create thread, so it may not be recommended behavior for Object Oriented Programming.