Executor : We can compare a java executor as guardian of thread pool.executor assign work to thread by peeking a them from pool.
Thread Pool: We can compare a pool with a storage room.
Traditional way thread programming :
a. By extending a thread class.
b. By implementing Runnable interface.
One Traditional Example :
- This program creates two thread and runs them separately.
- TestPrintNumbersThread .java
package com.sandeep.threads;
public class TestPrintNumbersThread {
public static void main(String[] args) {
PrintNumbersThread printEvennumThread = new PrintNumbersThread(
NumberType.EVEN.toString());
printEvennumThread.run();
PrintNumbersThread printOddnumThread = new PrintNumbersThread(
NumberType.ODD.toString());
printOddnumThread.run();
}
}
- PrintNumbersThread.java
package com.sandeep.threads;
public class PrintNumbersThread implements Runnable {
private String threadtype;
public PrintNumbersThread(String threadtype) {
this.threadtype = threadtype;
}
@Override
public void run() {
printNumbers(threadtype);
}
private void printNumbers(String threadtype) {
NumberType numtype = NumberType.valueOf(threadtype);
switch (numtype) {
case EVEN:
printEvenNumbers();
break;
case ODD:
printOddNumbers();
break;
}
}
private void printOddNumbers() {
for (int i = 0; i <= 20; i++) {
if (i % 2 != 0) {
System.out.println("O:" + i + " ");
}
}
}
private void printEvenNumbers() {
for (int i = 0; i <= 200; i++) {
if (i % 2 == 0) {
System.out.println("E:" + i + " ");
}
}
}
}
- NumberType.java
package com.sandeep.threads;
public enum NumberType {
EVEN,ODD
}
- New Executor Way:-
package com.sandeep.threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPrintNumbersThread {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
PrintNumbersThread printEvennumThread = new PrintNumbersThread(
NumberType.EVEN.toString());
executor.execute(printEvennumThread);
PrintNumbersThread printOddnumThread = new PrintNumbersThread(
NumberType.ODD.toString());
executor.execute(printOddnumThread);
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
}
Benefit :
- Executor will create the life cycle of each thread.
- Load balance and reliability. If one thread is corrupted in between then other thread will take the job.