Thread , Runnable and ExecutorService
Previous approach to create a thread.
1. Directly create an object of Thread Class after overriding the public void run() method of Thread class and call the start method to initiate the thread
package com.executor;
public class OldThread implements Runnable {
private String task;
public OldThread() {
super();
}
public OldThread(String task){
super();
this.task = task;
}
@Override
public void run(){
System.out.println( " Old thread runnable " + this.task);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.task + " completed.");
}
}
2. Implement the Runnable interface and override the public void method and pass the reference of Runnable Object reference into Thread(Runnable) constructor. call the start method to initiate the thread
package com.executor;
public class OldThreadRunnable {
public static void main(String [] args) {
for (int i = 1; i <= 5; i++) {
OldThread task = new OldThread("Task " + i);
Thread t1 = new Thread (task);
t1.start();
}
}
}
ExecutorService use the thread pool to execute the task. Executors.newFixedThreadPool(3);
Then new way to create, submit and execute thread by using ExecutorService interface.
in case of executor service just submit the task and no need to call the start() method.
package com.executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class OldThreadRunnable {
public static void main(String [] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
OldThread task = new OldThread("Task " + i);
executorService.submit(task);
}
}
}
public interface ExecutorService extends java.util.concurrent.Executor.
Executor provide methods to manage termination and methods that can produce a Future for tracking the
asynchronous tasks. submit(Runnable reference) method extends base method of Executor.exeute(Runnable)
by creating and returning the Future that can be used to cancel execution or wait for completion
Comments
Post a Comment