日期:2014-05-16 浏览次数:20587 次
public class TaskDispatchController { Set threadSet = new HashSet(); /** * 启动子线线程做事情 */ private void startThread() { //重用线程对象 ImportThread[] thread = importTool.getImportThread(); threadList = new ArrayList(thread.length); for (int i = 0; i < thread.length; i++) { ImportThread impThread = thread[i]; //子线程注册自己 threadSet.add(impThread); impThread.setController(this); new Thread(impThread).start(); } checkQuite(); } /** * 注销自己,并唤醒主线程检查是否可以退出 */ public synchronized void unregister(ImportThread thread) { threadSet.remove(thread); notifyAll(); } /** * */ private synchronized void checkQuite() { try { while (!threadSet.isEmpty()) { wait(); } backThread(); } catch (InterruptedException e) { throw new ThreadOperationException("main thread exception", e); } finally { close(); } } } public class ImportThread { TaskDispatchController taskDispatchController = null; public void setController(TaskDispatchController taskDispatchController ) { this.taskDispatchController = taskDispatchController ; } public void run() { if (taskDispatchController == null) { return; } //做某事情 [b]taskDispatchController.doXXX();[/b] while (true) { // do something } //执行完事情后结束 release(); } private void release() { if (taskDispatchController != null) { taskDispatchController .unregister(this); } [b]taskDispatchController == null;[/b] } }
public synchronized void unregister(ImportThread thread) { threadSet.remove(thread); thread.setController(null); notifyAll(); }
voliate boolea staredAll =