在Linux下多线程的问题
最近做的程序出现了一个多线程的问题,肯定是同步引起的,但是我个人还是不太理解,因为同样一段代码在Windows下运行正常,在Linux下就处理一堆问题了。
程序思想是这样子的,有多个任务需要处理,每次主线程处理一个任务,并把这个任务分成多个子任务让子线程去处理。在主线程中启动多个子线程去做事情,并注册自己。主线程就不断的检查是所有线程已经注销了,子线程做完事情后,会向主线程销自己,然后结束。
代码如下:
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(); }private void release() { if (taskDispatchController != null) { taskDispatchController .unregister(this); } } /** * 注销自己,并唤醒主线程检查是否可以退出 */ public synchronized void unregister(ImportThread thread) { try { while(!startedAll) { wait(); } } catch(InterruptedException e) { // doNothing } //将引用的controller置为null threadSet.setController(null); threadSet.remove(thread); notifyAll(); }