Create a thread pool with the Executors utility class

  The multi-threading technology mainly solves the problem of executing multiple threads in the processor unit, which can significantly reduce the idle time of the processor unit and increase the throughput of the processor unit.  

  The thread pool is mainly used to solve the problem of thread life cycle overhead and insufficient resources. By reusing threads for multiple tasks, the overhead of thread creation is amortized over multiple tasks, and since threads already exist by the time the request arrives, the delay introduced by thread creation is eliminated. This way, requests can be serviced immediately, making the application more responsive. In addition, resource starvation can be prevented by appropriately adjusting the number of threads in the thread pool.

  The Executors tool class provided in JDK5 can create four types of thread pools, as follows:

  (1) Executors.newCachedThreadPool(): Create a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, idle threads can be flexibly recovered; if there is no recovery, a new thread will be created.

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace ();
}
 
cachedThreadPool.execute(new Runnable() {
 
@Override
public void run() {
System.out.println(index);
}
});
}

 

  The thread pool is infinite. When the second task is executed, the first task has been completed, and the thread executing the first task will be reused instead of creating a new thread each time.

 

  (2) Executors.newFixedThreadPool: Create a fixed-length thread pool, which can control the maximum concurrent number of threads, and the excess threads will wait in the queue.

 

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
 
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
});
}

 

   Because the thread pool size is 3, each task sleeps for 2 seconds after outputting the index, so 3 numbers are printed every two seconds.

 

  The size of the fixed-length thread pool is best set according to system resources. Such as Runtime.getRuntime().availableProcessors().

 

  (3) Executors.newScheduledThreadPool: Create a fixed-length thread pool to support timing and periodic task execution.

 

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
 
@Override
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);

 

   Indicates a delay of 3 seconds to execute.  

 

scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
 
@Override
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);

 

   Indicates that it will be executed every 3 seconds after a delay of 1 second.

 

  ScheduledExecutorService is safer and more powerful than Timer.

 

  (4) Executors.newSingleThreadExecutor(): Create a single-threaded thread pool, which only uses a single worker thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

 

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
 
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
});
}

 

   The results are output in sequence, which is equivalent to executing each task in sequence.

 

  Most GUI programs today are single-threaded.

 

  The role of the thread pool:

 

  The number of threads created and destroyed is reduced, and each worker thread can be reused to perform multiple tasks. Depending on the environment of the system, the number of threads can be set automatically or manually to achieve the best results.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326053381&siteId=291194637