import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadingExecutor {
public static void main(String[] argv){
// Create the executor service with 3 Workers
ExecutorService executor = Executors.newFixedThreadPool(3);
String pattern = "yyyy-MM-dd hh:mm:ss aa";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
// Write the time in the logs
System.out.println( "Starting process at:\t" + simpleDateFormat.format( new Date() ) );
// Create all the workers and call the executor
for (int i = 0; i < 5; i++) {
Runnable worker = new Worker(i);
executor.execute(worker);
}
// Call the shutdown method of the executor
executor.shutdown();
// Wait for the executors to be terminated
while (!executor.isTerminated()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println( "Done processing at:\t" + simpleDateFormat.format( new Date() ) );
}
}
/**
* Worker class implementing Runnable
*/
class Worker implements Runnable {
// Internal Id of the Thread
private int id;
/**
* Constructor with an id
*/
Worker(int id){
this.id = id;
}
@Override
public void run() {
// Date pattern
String pattern = "yyyy-MM-dd hh:mm:ss aa";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
System.out.println( "Starting Thread " + id + " at\t" + simpleDateFormat.format( new Date() ));
// Call the process method
process();
System.out.println( "Thread " + id + " completed" + " at\t" + simpleDateFormat.format( new Date() ));
}
/**
* Process method
*/
public void process(){
// Wait for 2 seconds
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Starting process at: 2017-01-24 06:36:08 PM Starting Thread 0 at 2017-01-24 06:36:08 PM Starting Thread 1 at 2017-01-24 06:36:08 PM Starting Thread 2 at 2017-01-24 06:36:08 PM Thread 1 completed at 2017-01-24 06:36:10 PM Thread 0 completed at 2017-01-24 06:36:10 PM Thread 2 completed at 2017-01-24 06:36:10 PM Starting Thread 4 at 2017-01-24 06:36:10 PM Starting Thread 3 at 2017-01-24 06:36:10 PM Thread 4 completed at 2017-01-24 06:36:12 PM Thread 3 completed at 2017-01-24 06:36:12 PM Done processing at: 2017-01-24 06:36:12 PM
The code first create a ExecutorService with 3 threads:
// Create the executor service with 3 Workers ExecutorService executor = Executors.newFixedThreadPool(3);
// Create all the workers and call the executor
for (int i = 0; i < 5; i++) {
Runnable worker = new Worker(i);
executor.execute(worker);
}
// Call the shutdown method of the executor
executor.shutdown();
// Wait for the executors to be terminated
while (!executor.isTerminated()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
java.util.concurrent.Executors