likes
comments
collection
share

threadPoolExecutor

作者站长头像
站长
· 阅读数 43

1、线程池ThreadPoolExecutor的使用,队列的使用:SynchronousQueue not hold task,handoff task to thread,so it will false when dont have thread to procee the task ,or create a new thread to process the task,general,会设置最大线程无边界一起使用,LinkedBlockingQueue,Unbouded queue,the maxmumpoolSize is not effect,for example in a web page is useful in smooth out transient bursts of request.ArrayBlockingQueue,bouded queue.2、how to judge a thread is idle?线程在getTask时候,判断核心线程是否可以超时或者线程数是否大于核心线程,上一步如果为true表示需要有可能需要淘汰线程,然后带超时参数区获取task,如果超时后仍未获取道任务,则可以判断线程是空闲的,需要减少工作线程数并停止该线程。3、submit和execute用哪个方法来执行任务。都可以,submit return future ,you can get a reslut.execute just perform.4、线程池worker线程工作原理:首先execute(runnable),添加第一个任务,此时线程数少于核心线程数,构建worker线程,worker本身是一个runnable,成员变量其中包含一个firstTask和一个thread(this),构建好了之后,调用worker.thread.start(),worker.run会执行,执行过程中,会判断firstTask,如果存在则执行firstTask,否则判断getTask存不存在任务,getTask又会调用阻塞队列,有任务时会执行从队列中取到的任务。现在来说当核心线程已满时的处理过程,就是会把任务放到阻塞队列,因为之前执行过firstTask任务之后的线程会调用getTask,所以会取到后添加的任务。所以可以重用线程继续执行。

转载自:https://segmentfault.com/a/1190000042104112
评论
请登录