java multi-threading and thread pool

1. Scene Description

Multithreading is also commonly used before, this time because of the need to use multiple threads on another page, as shown below, under summary, a friend in need can refer to.

2. Solution

2.1 thread pool concept

The official definition of the thread pool is not to say, under the popular saying: the concept of the pond, in advance (pre-defined) is created, subsequent thread can take directly from the pond, the benefits:

(1) to create a thread more consumption of resources, without recreating;

(2) pool be defined first, create a thread to avoid uncontrolled, cause the system to unpredictable risks.

2.2 Creating ways

Create a way using jdk own thread pool, jdk1.5 started to provide, in the following package of java.util.concurrent.

There are two ways to create the surface, in fact, one kind.

(1) is the use of new ThreadPoolExecutor created;

  public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {

(2) is the use of Executors.newFixedThreadPool (3), but the thread pool or calling new ThreadPoolExecutor be created, assigning several default parameters only.

new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());

2.3 Definition

A total of seven parameters:

(1)corePoolSize

The core number of threads, when there are tasks come in, if the current number of threads has not yet reached the number corePoolSize, create kernel threads, kernel threads have the following characteristics:

1, when the number of threads has not reached the maximum core thread, new tasks come in, even if there is idle threads will not reuse, is still the core of the new thread; 2, core threads are generally not destroyed, even idle state, but if allowCoreThreadTimeOut (boolean value) by the method is set to true, the timeout will also be destroyed; 3, when the production environment is first initialized, you can call prestartCoreThread () method to create in advance all core threads, the first call to avoid slow;

(2)maximumPoolSize

In addition to the core thread, the thread when the core strategy is to some completely free time, but also create some temporary thread to handle the task, maximumPoolSize is the maximum limit core thread + temporary thread. Temporary thread has a timeout mechanism, exceeding the set idle time thing is not dry, it will be destroyed.

(3)keepAliveTime

This is the timeout parameters in the two above mentioned, which is the maximum thread idle time, the default non-core thread is used by the allowCoreThreadTimeOut (boolean value) method sets, it will be used for the core thread.

(4)unit

KeepAliveTime this parameter with the above, the specified time-out unit, in seconds, minutes, hours, etc.

(5)workQueue

Task queue waiting to be executed, if the core thread is not idle, and the new task will be placed in the waiting queue.

(6)threadFactory

It is an interface for generating ways to achieve thread, the thread name format is defined, whether the background and so on, you can use Executors.defaultThreadFactory () default implementation can be, can also be achieved by methods such as Guava-party library, if there are special requirements, then you can define your own. It should be the most important place is the definition of the thread name format, easy to troubleshoot it.

(7)handler

When there is no idle thread processing tasks, and the queue is full (of course, this only works for a bounded queue), and then there are new tasks come in, you do some trade-offs, while this parameter is to specify the policy trade-offs, there are the following four kind of strategy can be selected:

ThreadPoolExecutor.AbortPolicy: direct throw an exception, which is the default strategy;
ThreadPoolExecutor.DiscardPolicy: discards the task, but does not throw an exception.
ThreadPoolExecutor.DiscardOldestPolicy: discard the foremost task queue, and then the new task added to the waiting queue
ThreadPoolExecutor.CallerRunsPolicy: thread from the thread pool where the processing tasks, such as creating a thread pool in the main function, if the implementation of this policy, there will be main thread to perform the task

2.4 Test validation

2.4.1 Test thread
package com.yutong.laowang.test;

public class ThreadTest extends Thread{
    @Override
    public void run() {
        System.out.println("软件老王:" +Thread.currentThread().getName());
  }
}
2.4.2 Executors create
  private static void test4() {
        Executor mExecutor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            Thread thread = new ThreadTest();
            mExecutor.execute(thread);
        }
    }

result:

软件老王:pool-2-thread-2
软件老王:pool-2-thread-3
软件老王:pool-2-thread-1
软件老王:pool-2-thread-3
软件老王:pool-2-thread-2
软件老王:pool-2-thread-1
软件老王:pool-2-thread-3
软件老王:pool-2-thread-2
软件老王:pool-2-thread-3
软件老王:pool-2-thread-1
2.4.3 ThreadPoolExecutor create
 private static void test3() {
        int poolSize = 5;
        int queueSize = 100;
        ExecutorService executorService = new ThreadPoolExecutor(poolSize, poolSize, 0L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(queueSize), new ThreadPoolExecutor.AbortPolicy());
                
        for (int i=0;i<10;i++) {
            executorService.submit(new ThreadTest());
        }
    }

result:

软件老王:pool-2-thread-1
软件老王:pool-2-thread-3
软件老王:pool-2-thread-4
软件老王:pool-2-thread-2
软件老王:pool-2-thread-5
软件老王:pool-2-thread-5
软件老王:pool-2-thread-1
软件老王:pool-2-thread-2
软件老王:pool-2-thread-2
软件老王:pool-2-thread-1
2.4.4 Thread disabled
thread.interrupt();
---有时候不一定能执行成功,一般会结合判断使用,软件老王,例如:
在ThreadTest类中进行判断,默认为false,当满足条件下为true,停用线程。
 public volatile boolean exit = false;

I'm "Software Pharaoh," I felt that if I may, to focus the next chant, subsequent updates seconds to know! Welcome forum, No. namesake public message exchange!

Guess you like

Origin www.cnblogs.com/ruanjianlaowang/p/12014490.html