Created
February 6, 2012 08:37
-
-
Save yongboy/1750798 to your computer and use it in GitHub Desktop.
ForkJoinWorkerThread.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 用于执行ForkJoinTask | |
public class ForkJoinWorkerThread extends Thread { | |
final ForkJoinPool.WorkQueue workQueue; // 可以用于工作窃取的双端队列 | |
final ForkJoinPool pool; // 工作线程池 | |
protected ForkJoinWorkerThread(ForkJoinPool pool) { | |
super(pool.nextWorkerName()); | |
setDaemon(true); // 将该线程标记为守护线程 | |
Thread.UncaughtExceptionHandler ueh = pool.ueh; | |
if (ueh != null) | |
setUncaughtExceptionHandler(ueh); // 设置当前线程由于未捕获到异常而突然终止时调用的处理函数 | |
this.pool = pool; | |
this.workQueue = new ForkJoinPool.WorkQueue(this, pool.localMode); // 构造一个任务队列,用于存放分解的任务 | |
pool.registerWorker(this); // 注册工作线程到工作线程池中 | |
} | |
public ForkJoinPool getPool() { | |
return pool; | |
} | |
/** | |
* 返回当前工作线程在池中索引位置 | |
*/ | |
public int getPoolIndex() { | |
return workQueue.poolIndex; | |
} | |
// 在处理任务之前初始化一些状态,在重写时,需要注意一定要在第一行位置调用super.onStart() | |
protected void onStart() { | |
} | |
// 资源清理用途,重写时,需要在最后一行调用super.onTermination(exception)函数。 | |
protected void onTermination(Throwable exception) { | |
} | |
/** | |
* 用于循环执行ForkJoinTask任务队列 | |
*/ | |
public void run() { | |
Throwable exception = null; | |
try { | |
onStart(); // 初始化状态 | |
pool.runWorker(this); | |
} catch (Throwable ex) { | |
exception = ex; | |
} finally { | |
try { | |
onTermination(exception); // 资源清理 | |
} catch (Throwable ex) { | |
if (exception == null) | |
exception = ex; | |
} finally { | |
pool.deregisterWorker(this, exception); // 注销当前线程 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment