構造方法javascript
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
BlockingQueue經常使用的3個實現類java
LinkedBlockingQueue的數據吞吐量要大於ArrayBlockingQueue,但在線程數量很大時其性能的可預見性低於ArrayBlockingQueue. SynchronousQueue初始化後必須先有其餘線程對其使用take()方法後才能使用put() 或者 offer()方法微信
下面是線程池核心的執行代碼,只看懂一點:cry:併發
final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts boolean completedAbruptly = true; try { //它在執行完一個線程會getTask再去取一個,直到沒有任務。 while (task != null || (task = getTask()) != null) { w.lock(); //.......刪除N行代碼 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); } }
gettask方法性能
private Runnable getTask() { boolean timedOut = false; // Did the last poll() time out? for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) { decrementWorkerCount(); return null; } //......省略N行代碼 try { Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take(); if (r != null) return r; timedOut = true; } catch (InterruptedException retry) { timedOut = false; } } }
這裏用到了BlockingQueue的方法,很巧妙的使用。timed是判斷這個線程是否能夠回收,由咱們設置的allowCoreThreadTimeOut和當前線程池線程大小決定的。當要回收,用的是poll方法,不能回收用的是take方法阻塞線程線程
提個問題,線程池有兩種提交方式execute()和submit()區別,能夠在評論區討論哦!請關注微信公衆號,查看,嘻嘻。不過之後會在評論區回覆的!!rest
歡迎關注個人微信公衆號cobs-snail,讓咱們一塊兒前進吧!!code