Java Thread Pool - ThreadPoolExecutor Example
WorkerThread.java
http://www.javaiq.in/2019/06/how-to-create-custom-thread-pool.html
WorkerThread.java
package com.shubh.threadpool;
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s) {
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.command;
}
}
TestThreadPool.java
package com.shubh.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
Output:
pool-1-thread-4 Start. Command = 3
pool-1-thread-2 Start. Command = 1
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-3 End.
pool-1-thread-2 End.
pool-1-thread-1 End.
pool-1-thread-2 Start. Command = 5
pool-1-thread-1 Start. Command = 6
pool-1-thread-3 Start. Command = 7
pool-1-thread-5 End.
pool-1-thread-4 End.
pool-1-thread-5 Start. Command = 8
pool-1-thread-4 Start. Command = 9
pool-1-thread-2 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-4 End.
pool-1-thread-5 End.
Finished all threads
Q- How To Create custom thread Pool in java?http://www.javaiq.in/2019/06/how-to-create-custom-thread-pool.html
Related Tutorials
- Lock Interface In Concurrency API
- Lock In Java Example
- StampedLock With Examples
- Differences between Lock and Synchronized block
- Method And Block Synchronization In Java Example
- How To Create Custom Lock
- Fair Lock In Java Example
- Synchronization Vs Lock in java
- Thread Pool - ThreadPoolExecutor Example
- How To Create Custom Thread Pool
- How ConcurrentHashMap Works Internally
- newsinglethreadexecutor vs newfixedthreadpool
- Future Vs Completablefuture
- ExecutorService vs ExecutorCompletionService in Java
- Callable Interface Example
- CompletableFuture
- ExecutorCompletionService
- Method And Block Synchronization
- ConcurrentHashMap
- Differences Between Submit and Execute methods
- Difference Between Callable and Runnable Interface in Java
No comments:
Post a Comment