您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java线程池execute()方法怎么用

2025/10/20 1:26:20发布25次查看
先理解线程池到底有什么作用* thread pools address two different problems: they usually* provide improved performance when executing large numbers of* asynchronous tasks, due to reduced per-task invocation overhead,* and they provide a means of bounding and managing the resources,* including threads, consumed when executing a collection of tasks.* each {@code threadpoolexecutor} also maintains some basic* statistics, such as the number of completed tasks.
线程池处理了两个不同的问题,线程池通过减少线程正式调用之前的开销来给大量异步任务更优秀的表现,与此同时给出了一系列绑定管理任务线程的一种手段。每个线程池都包含了一些基本信息,比如内部完成的任务数量。
先看threadpoolexecutor类的一系列代表状态的private final atomicinteger ctl = new atomicinteger(ctlof(running, 0));private static final int count_bits = integer.size - 3;private static final int capacity = (1 << count_bits) - 1; private static final int running = -1 << count_bits;private static final int shutdown = 0 << count_bits;private static final int stop = 1 << count_bits;private static final int tidying = 2 << count_bits;private static final int terminated = 3 << count_bits; private static int runstateof(int c) { return c & ~capacity; }private static int workercountof(int c) { return c & capacity; }private static int ctlof(int rs, int wc) { return rs | wc; }
ctl作为atomicinteger类存放了类中的两种信息,在其中由高3位来保存线程池的状态,后29位来保存此时线程池中的woker类线程数量(由此可知,线程池中的线程数量最高可以接受大约在五亿左右)。由此可见给出的runstateof()和workercountof()方法分别给出了查看线程状态和线程数量的方法。
该类一共给出了五种状态让我们看作者给出的注释
* running: accept new tasks and process queued tasks* shutdown: don't accept new tasks, but process queued tasks* stop: don't accept new tasks, don't process queued tasks,* and interrupt in-progress tasks* tidying: all tasks have terminated, workercount is zero,* the thread transitioning to state tidying* will run the terminated() hook method* terminated: terminated() has completed
running状态可以接受新进来的任务,同时也会执行队列里的任务。
shutdown 状态已经不会再接受新任务,但仍旧会处理队列中的任务。
stop状态在之前的基础上,不会处理队列中的人物,在执行的任务也会直接被打断。
tidying状态在之前的基础上,所有任务都已经终止,池中的worker线程都已经为0,也就是stop状态在清理完所有工作线程之后就会进入该状态,同时在shutdown状态在队列空以及工作线程清理完毕之后也会直接进入这个阶段,这一阶段会循环执行terminated()方法。
terminated 状态作为最后的状态,在之前的基础上terminated()方法也业已执行完毕,才会从上个状态进入这个状态,代表线程池已经完全停止。
由于线程池的状态都是通过atomicinteger来保存的,可以通过比较的方式简单的得到当前线程状态。
private final blockingqueue<runnable> workqueue; private final reentrantlock mainlock = new reentrantlock(); private final hashset<worker> workers = new hashset<worker>(); private final condition termination = mainlock.newcondition(); private int largestpoolsize; private long completedtaskcount; private volatile threadfactory threadfactory; private volatile rejectedexecutionhandler handler; private volatile long keepalivetime; private volatile boolean allowcorethreadtimeout; private volatile int corepoolsize; private volatile int maximumpoolsize;
接下来是线程池的几个有关工作线程的变量corepoolsize表示线程池中允许存活最少的工作线程数量,但值得注意的是如果allowcorethreadtimeout一旦设置true(默认false),每个线程的存活时间只有keepalivetime也就是说在allowcorethreadtimeout为true的时候,该线程池最小的工作线程数量为0;maximumpoolsize代表线程池中最大的工作线程数量。
keepalivetime为线程池中工作线程数量大于corepoolsize时,每个工作线程的在等待工作时最长的等待时间。
workqueue作为线程池的任务等待队列,这个将在接下来的execute()里详细解释。
workers作为存放线程池中存放工作线程的容器。
largestpoolsize用来记录线程池中存在过的最大的工作线程数量。
completedtaskcount用来记录线程池完成的任务的总数。
handler作为线程池中在不能接受任务的时候的拒绝策略,我们可以实现自己的拒绝策略,在实现了rejectedexecutionhandler接口的前提下。下面是线程池的默认拒绝策略,
public void rejectedexecution(runnable r, threadpoolexecutor e) { throw new rejectedexecutionexception("task " + r.tostring() + " rejected from " + e.tostring());}
threadfactory作为线程池生产线程的工厂类
下面是线程池默认的线程工厂的生产线程方法public thread newthread(runnable r) { thread t = new thread(group, r, nameprefix + threadnumber.getandincrement(), 0); if (t.isdaemon()) t.setdaemon(false); if (t.getpriority() != thread.norm_priority) t.setpriority(thread.norm_priority); return t;}
我们可以先看我们最常调用的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);}
execute()内部的调用逻辑非常清晰。
如果当前线程池的工作线程数量小于corepoolsize,那么直接调用addwoker(),来添加工作线程。
下面是addworker()的具体方法private boolean addworker(runnable firsttask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runstateof(c); if (rs >= shutdown && ! (rs == shutdown && firsttask == null && ! workqueue.isempty())) return false; for (;;) { int wc = workercountof(c); if (wc >= capacity || wc >= (core ? corepoolsize : maximumpoolsize)) return false; if (compareandincrementworkercount(c)) break retry; c = ctl.get(); // re-read ctl if (runstateof(c) != rs) continue retry; } } boolean workerstarted = false; boolean workeradded = false; worker w = null; try { final reentrantlock mainlock = this.mainlock; w = new worker(firsttask); final thread t = w.thread; if (t != null) { mainlock.lock(); try { int c = ctl.get(); int rs = runstateof(c); if (rs < shutdown || (rs == shutdown && firsttask == null)) { if (t.isalive()) throw new illegalthreadstateexception(); workers.add(w); int s = workers.size(); if (s > largestpoolsize) largestpoolsize = s; workeradded = true; } } finally { mainlock.unlock(); } if (workeradded) { t.start(); workerstarted = true; } } } finally { if (! workerstarted) addworkerfailed(w); } return workerstarted;}
这段方法比较长,但整体的逻辑还是清晰的。
首先判断当前线程池的状态,如果已经状态不是shutdown或者running,或者已经为shutdown但是工作队列已经为空,那么这个时候直接返回添加工作失败。接下来是对线程池线程数量的判断,根据调用时的core的值来判断是跟corepoolsize还是 maximumpoolsize判断。
在确认了线程池状态以及线程池中工作线程数量之后,才真正开始添加工作线程。
新建立一个worker类(线程池的内部类,具体的工作线程),将要执行的具体线程做为构造方法中的参数传递进去,接下来将其加入线程池的工作线程容器workers,并且更新工作线程最大量,最后调用worker工作线程的start()方法,就完成了工作线程的建立与启动。
让我们回到execute()方法,如果我们在一开始的线程数量就大于corepoolsize,或者我们在调用addworker()方法的过程中出现了问题导致添加工作线程数量失败,那么我们会继续执行接下来的逻辑。
在判断完毕线程池的状态后,则会将任务通过workqueue.offer())方法试图加进任务队列。offer()方法的具体实现会根据在线程池构造方法中选取的任务队列种类而产生变化。
但是如果成功加入了任务队列,仍旧需要注意判断如果线程池的状态如果已经不是running那么会拒绝执行这一任务并执行相应的拒绝策略。在最后需要记得成功加入队列成功后如果线程池中如果已经没有了工作线程,需要重新建立一个工作线程去执行仍旧在任务队列中等待执行的任务。
如果在之前的前提下加入任务队列也失败了(比如任务队列已满),则会在不超过线程池最大线程数量的前提下建立一个工作线程来处理。
如果在最后的建立工作线程也失败了,那么我们只有很遗憾的执行任务的拒绝策略了。
在之前的过程中我们建立了工作线程worker()类,那么我们现在看看worker类的内部实现,也可以说是线程池的核心部分。
worker类作为线程池的内部类接下来是worker()类的成员
final thread thread; runnable firsttask; volatile long completedtasks;
thread作为worker的工作线程空间,由线程池中所设置的线程工厂生成。
firsttask则是worker在构造方法中所接受到的所要执行的任务。
completedtasks作为该worker类所执行完毕的任务总数。
接下来我们可以看最重要的,也就是我们之前建立完worker类之后立马调用的run()方法了
public void run() { runworker(this);}
run()方法实现的很简单我们可以继续追踪下去
final void runworker(worker w) { thread wt = thread.currentthread(); runnable task = w.firsttask; w.firsttask = null; w.unlock(); boolean completedabruptly = true; try { while (task != null || (task = gettask()) != null) { w.lock(); 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); }}
如果这个worker还没有执行过在构造方法就传入的任务,那么在这个方法中,会直接执行这一任务,如果没有,则会尝试去从任务队列当中去取的新的任务。
但是在真正调用任务之前,仍旧会判断线程池的状态,如果已经不是running亦或是shutdwon,则会直接确保线程被中断。如果没有,将会继续执行并确保不被中断。
接下来可见,我们所需要的任务,直接在工作线程中直接以run()方式以非线程的方式所调用,这里也就是我们所需要的任务真正执行的地方。
在执行完毕后,工作线程的使命并没有真正宣告段落。在while部分worker仍旧会通过gettask()方法试图取得新的任务。
下面是gettask()的实现private runnable gettask() { boolean timedout = false; retry: for (;;) { int c = ctl.get(); int rs = runstateof(c); if (rs >= shutdown && (rs >= stop || workqueue.isempty())) { decrementworkercount(); return null; } boolean timed; for (;;) { int wc = workercountof(c); timed = allowcorethreadtimeout || wc > corepoolsize; if (wc <= maximumpoolsize && ! (timedout && timed)) break; if (compareanddecrementworkercount(c)) return null; c = ctl.get(); if (runstateof(c) != rs) continue retry; } try { runnable r = timed ? workqueue.poll(keepalivetime, timeunit.nanoseconds) : workqueue.take(); if (r != null) return r; timedout = true; } catch (interruptedexception retry) { timedout = false; } }}
首先仍旧会判断线程池的状态是否是running还是shutdown以及stop状态下队列是否仍旧有需要等待执行的任务。如果状态没有问题,则会跟据allowcorethreadtimeout和corepoolsize的值通过对前面这两个属性解释的方式来选择从任务队列中获得任务的方式(是否设置timeout)。其中的timedout保证了确认前一次试图取任务时超时发生的记录,以确保工作线程的回收。
在runworker()方法的最后调用了processworkerexist()方法来执行工作线程的回收。
private void processworkerexit(worker w, boolean completedabruptly) { if (completedabruptly) decrementworkercount(); final reentrantlock mainlock = this.mainlock; mainlock.lock(); try { completedtaskcount += w.completedtasks; workers.remove(w); } finally { mainlock.unlock(); } tryterminate(); int c = ctl.get(); if (runstatelessthan(c, stop)) { if (!completedabruptly) { int min = allowcorethreadtimeout ? 0 : corepoolsize; if (min == 0 && ! workqueue.isempty()) min = 1; if (workercountof(c) >= min) return; } addworker(null, false); }}
在这一方法中,首先确保已经重新更新了线程池中工作线程的数量,之后从线程池中的工作线程容器移去当前工作线程,并且将完成的任务总数加到线程池的任务总数当中。
在最后仍旧要确保线程池中依旧存在大于等于最小线程数量的工作线程数量存在,如果没有,则重新建立工作线程去等待处理任务队列中任务。
以上就是java线程池execute()方法怎么用的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product