构造方法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