Java How to Fix Size Thread Pool
- 2021-09-20 20:44:23
- OfStack
1. Introduction to Fixed-Size Thread Pool
Thread pool is to set up several usable threads and put them there when the program starts. Then wait for the specific task to be put in, which can basically be said to be the implementation class of Runnable, so it reduces the overhead of creating and destroying threads every time, but at the same time increases the overhead of maintaining these threads, depending on the specific situation.
A fixed-size thread pool is where a fixed number of threads are created at startup time and put in place to be used.
2. Wrap a thread pool object
public class TaskPool{
private final ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(9); // Create 1 The size is 9 Fixed thread pool of, you can follow CPU Preliminary determination of the audit, if CPU Intensive tasks create N+1 A, if it is IO Intensive tasks are created 2N+1 Of which N I.e. CPU Audit of
protected void shutdown(){
// do something
// This method waits for all submitted tasks in the thread pool to finish execution, does not receive new tasks, and then ends
executor.shutdown();
// This forces the end of all tasks, and then the waiting task list
// executor.shutdownNow();
}
protected void execute(Runnable command){
// do something
// Submit a task
executor.execute(command);
}
public void status(){
StringBuffer sb = new StringBuffer();
// The number of threads currently executing the task
sb.append(executor.getActiveCount() + "\n");
// Number of threads currently waiting to execute
sb.append(executor.getQueue().size() + "\n");
// Returns the number of threads that have completed
sb.append(executor.getCompletedTaskCount() + "\n");
System.out.println(sb.toString());
// Note: All of the above methods return 1 Because these states will change at any time while the thread is executing
}
}
3. Use thread pools
public class Launcher{
private TaskPool taskPool = new TaskPool();
public static void main(String[] args){
// New 100 Tasks, Runnable Implementation class of Task
Task[] tasks = new Task[100];
for (int i = 0; i < tasks.length; i++){
tasks[i] = new Task("Task " + (i+1));
// Submit to thread pool to run
taskPool.execute(task[i]);
if ( i % 50 == 0){
taskPool.status();
}
}
private static class Task implements Runnable{
private String name;
public Task(String name){
this.name = name;
}
public void run(){
// do something
System.out.println(" My name is: " + this.name);
}
}
}
Small Expansion of Java Thread Pool
Introduction to Thread Pool
1 Common pooling techniques
C3P0
DBCP
2 Derivation of thread pool
It is very time consuming and resource consuming to create thread objects frequently and switch context between multiple threads, so thread pool technology is proposed in JDK 1.5
3 Using thread pools
Exector
4 Creation of thread pool
Create a fixed-size thread pool (most commonly used method)
ExecutorService pool = Executors.newFixedThreadPool(2);
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
};
pool.execute(task);
pool.execute(task);
pool.execute(task);// There are only two under the band of the thread pool This task is now queued in its wait queue
Create a variable-size thread pool
ExecutorService pool = Executors.newCachedThreadPool();
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
};
pool.execute(task);
pool.execute(task);
pool.execute(task);
Create a thread pool for independent tasks
ExecutorService pool = Executors.newSingleThreadExecutor();
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
};
pool.execute(task);
pool.execute(task);
pool.execute(task);
Create a schedulable thread pool
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(2);
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
};
threadPool.schedule(task, 2000, TimeUnit.MILLISECONDS);