VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • 简单看看ThreadPoolExecutor原理(4)

false; Worker w = null; try { //这里新建一个Worker,注意,这个Worker中存放了当前线程和实现了Runnable接口的具体任务 w = new Worker(firstTask); final Thread t = w.thread; if (t != null) { //独占锁,因为可能有多个线程同时执行execute方法 final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { //获取线程池状态 int rs = runStateOf(ctl.get()); if (rs < SHUTDOWN ||(rs == SHUTDOWN && firstTask == null)) { if (t.isAlive()) throw new IllegalThreadStateException(); //线程池状态满足条件的话将Worker添加到集合中 workers.add(w); int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; workerAdded = true; } } finally { //释放锁 mainLock.unlock(); } //到这里任务已经添加成功,再启动任务,由于在创建Worker的时候,构造器中使用的是 // this.thread = getThreadFactory().newThread(this); //注意,Worker实现了Runnable接口,于是就相当于Thread t = new Thread(worker),调用t.start()就是调用worker的run方法 if (workerAdded) { t.start(); workerStarted = true; } } } finally { if (! workerStarted) addWorkerFailed(w); } return workerStarted; } //启动线程的start方法,实际上启动的是worker中观的run方法 public void run() { runWorker(this); } final void runWorker(Worker w) { //获取当前线程 Thread wt = Thread.currentThread(); //获取当前Worker中的任务 Runnable task = w.firstTask; w.firstTask = null; //由于Worker也实现了AQS接口,这里就是将AQS中的state设置为0,允许中断, //因为其他线程可能会调用线程池的shutdownNow方法 w.unlock(); // allow interrupts boolean completedAbruptly = true; try { //如果当前Worker中的task==null或者从任务队列中获取task为空,就到这方法的最后执行清理工作,      //注意,这里就是线程池中的线程可以复用的关键,会不断的调用getTask()方法去任务队列中获取任务 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 { //执行任务,这里就是我们自己定义的实际任务的run方法 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; //统计当前的Worker完成了多少任务 w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { //执行清理工作 processWorkerExit

相关教程