자바 동시성 스레드 풀 프로필

자바 동시성 스레드 풀 프로필

왜 우리는 스레드 풀을 사용해야합니까?

우리는 우리 각 프로그램을 실행하는 스레드를 생성, 스레드가 상대적으로 비싼 자원 것을 알고, 사실, 운영 체제는 우리의 임무를 수행하기 위해 상응하는 스레드를 생성하고, 우리는 자주 만들고 스레드가 시스템 리소스를 소모하는 파괴 동시의 적은 수의 시스템에 거의 영향 것 같다, 그러나 동시에 많은 수의, 우리는 각 요청에 대한 스레드를 만들 때 다음 작업 후 파괴, 너무 자주 생성을 실행 일정을 기다릴 때, 파괴 스레드가 시스템 리소스를 소모한다.

스레드 풀 스레드가 다시 사용할 수 있기 때문에 우리가 스레드를 관리하는 스레드 풀을 사용하여,이 손실을 줄이기 위해 아주 좋은 일 수있다, 재사용 스레드는 무엇입니까? 어떤 스레드 풀 스레드, 그리고 작업 스레드가 끝난 실행 한 후하지 우리 자신은 같은 하나의 작업을 수행 할 스레드를 생성하고 풀의 스레드가 그 실행 논리는있다 while,이주기를 while주기 고도의 동시 환경의 경우 시스템 자원을 절약, 크게 운영 스레드의 생성과 파괴를 줄일 수있는, 스레드는 작업을 획득 계속하고 수행 (상황에 따라 작업이 있습니다).

의 스레드 풀의 소스 코드 일부를 살펴 보자 :

    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

Repeatedly gets tasks from queue and executes them이것은 위의 코멘트를하는 방법, 그리고 코드 방식의 의견은 매우 명확 스레드 풀 스레드가 다음 작업이 끝난 실행되지 않지만, 작업을 취득 이니셔티브 (반복) 소요됩니다 보여 실행.

스레드 풀 디자인

그것은 분명 프로그래밍 인터페이스를 지향한다.
그림 삽입 설명 여기
일부 속성 스레드 풀

그림 삽입 설명 여기
여기에 그림과 함께 소스 코드와 이러한 특성의 댓글이 이해하기 어려운 안이다.

    /**
     * Core pool size is the minimum number of workers to keep alive
     * (and not allow to time out etc) unless allowCoreThreadTimeOut
     * is set, in which case the minimum is zero.
     */
    private volatile int corePoolSize;
    /**
     * Maximum pool size. Note that the actual maximum is internally
     * bounded by CAPACITY.
     */
    private volatile int maximumPoolSize;
    /**
     * Timeout in nanoseconds for idle threads waiting for work.
     * Threads use this timeout when there are more than corePoolSize
     * present or if allowCoreThreadTimeOut. Otherwise they wait
     * forever for new work.
     */
    private volatile long keepAliveTime;
   /**
     * The queue used for holding tasks and handing off to worker
     * threads.  We do not require that workQueue.poll() returning
     * null necessarily means that workQueue.isEmpty(), so rely
     * solely on isEmpty to see if the queue is empty (which we must
     * do for example when deciding whether to transition from
     * SHUTDOWN to TIDYING).  This accommodates special-purpose
     * queues such as DelayQueues for which poll() is allowed to
     * return null even if it may later return non-null when delays
     * expire.
     */
    private final BlockingQueue<Runnable> workQueue;
    /**
     * Factory for new threads. All threads are created using this
     * factory (via method addWorker).  All callers must be prepared
     * for addWorker to fail, which may reflect a system or user's
     * policy limiting the number of threads.  Even though it is not
     * treated as an error, failure to create threads may result in
     * new tasks being rejected or existing ones remaining stuck in
     * the queue.
     *
     * We go further and preserve pool invariants even in the face of
     * errors such as OutOfMemoryError, that might be thrown while
     * trying to create threads.  Such errors are rather common due to
     * the need to allocate a native stack in Thread.start, and users
     * will want to perform clean pool shutdown to clean up.  There
     * will likely be enough memory available for the cleanup code to
     * complete without encountering yet another OutOfMemoryError.
     */
    private volatile ThreadFactory threadFactory;
    /**
     * Handler called when saturated or shutdown in execute.
     */
    private volatile RejectedExecutionHandler handler;

스레드 풀 구조
그림 삽입 설명 여기
스레드 풀 스레드를 생성

이 그림은 중국어로, 매우 선명한해야합니다, 당신은 그것을 설명 할 필요가 없습니다.
그림 삽입 설명 여기

스레드 풀 작업 거부

스레드 풀 작업 대기열이 가득하고 새 스레드 (도달 스레드의 수를 만들 수없는 경우 maximumPoolSize), 스레드 풀은 작업을 거부합니다. 사실, 여기에 작업을 거부합니다 다른 상황 스레드 풀은 모든 사람이 알고는, 스레드 풀은 작업을 거부 할 수 있도록하는 것입니다있다.
그림 삽입 설명 여기

여기에 우리가 자바 스레드 풀의 일반적인 이해를 가지고 있고, 구체적으로 원리를 설명하지 않았다, 결국, 또한 초보자 블로거를 더 보충 할 수있는 기회를 갖게됩니다 너무합니다.

게시 된 302 개 원래 기사 · 원 찬양 435 · 전망 710 000 +

추천

출처blog.csdn.net/qq_37960603/article/details/104334254