Java多線程 - 線程池詳解

1. 優勢

線程池的用處:原來是100個任務要有100個線程來執行任務,現在是100個任務我們只要幾個線程就可以執行任務了。

一個整合:ThreadPoolExecutor繼承了AbstractExecutorService繼承了ExecutorService繼承了Executor。

package com.roocon.thread.td4;
 
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.TimeUnit;
 
public class Demo {
	public static void main(String[] args) {
		//初始化的線程池的大小  最大的線程池的大小 存活的時間 天  阻塞隊列   飽和策略
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 50, 10, TimeUnit.DAYS, new ArrayBlockingQueue<>(10),new ThreadPoolExecutor.CallerRunsPolicy());
		AtomicInteger count = new AtomicInteger();
		for(int i = 0; i < 100 ;i ++) {
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName());
					count.getAndIncrement();
				}
			});
		}
		threadPool.shutdown();
		while(Thread.activeCount() > 1) {
		}
		System.out.println(count.get());
	}
 
}

 飽和策略,拿到隊列第一個任務並執行當前的任務,在構造函數裏面傳入就可以了。

換個策略,可以把任務執行完畢的。

上面的就是最原始的線程是的使用,接下來我們看下原理:

不是線程的隊列,是保存的是等待的執行的任務的隊列。

看下屬性:

ctl:線程池的狀態注意是,ctl是線程池的運行狀態。

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
   public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

我們再看下execute。執行之前我們的約定。

說明:

 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }

我們執行的任務會給我們包裝成爲一個內部類worker。

addWorker

在addWorker調用:

執行runWorker。

 runWorker

關閉線程池:

shutDown。

其實就是個標誌位

上面的對應:shutdown 和 shutdownNow

shutdownNow:殺掉的很徹底的,統統殺掉了。正在執行的也是殺掉了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章