Different ways to create thread in Java
What are the different ways to create a thread in Java?
1- By extending Thread class.
2- By implementing Runnable interface.
By extending Thread class
- Extend Thread class to define a thread in Java.
- Override the run method and define task inside the run method.
- Call start method on thread object to start the thread.
package com.javainstance;
/**
* @author javainstance
*
*/
public class Task extends Thread {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Thread in doing task : " + i);
}
}
public static void main(String[] args) {
Task task = new Task();
task.start();
}
}
By implementing Runnable interface
- Create a class and implement Runnable interface.
- Implementing runnable interface force you to implement the run method.
- Define task inside the run method.
- Create thread object by passing runnable object as an argument
- Call start method on thread object to start the thread.
package com.javainstance;
/**
* @author javainstance
*
*/
public class Task implements Runnable {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Thread in doing task : " + i);
}
}
public static void main(String[] args) {
Task task = new Task();
Thread thread = new Thread(task);
thread.start();
}
}
Creating thread using anonymous class
Sometimes it is handy to create a thread using an anonymous class when the thread is just to run a method.In below example thread is created using an anonymous class.
package com.javainstance;
/**
* @author javainstance
*
*/
public class Task {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Thread in doing task : " + i);
}
}
});
thread.start();
}
}
Output is same above 3 programs:
Thread in doing task : 0
Thread in doing task : 1
Thread in doing task : 2
Synchronization in Java - Synchronized keyword
Give your suggestion in comments.
If you like the post Share with your friends on social network.
Follow us: www.facebook.com/javainstance
Follow us: www.facebook.com/javainstance
Different ways to create thread in Java
Reviewed by JavaInstance
on
10:17:00 AM
Rating:
Reviewed by JavaInstance
on
10:17:00 AM
Rating:

No comments: