近期,写了一段多线程的代码,主要想用多线程来解析一堆文件,这样比单线程要快;但是我还需要跟踪最后的结果,就是我主线程要hold住,直到各子线程都完毕了,再继续走;
如下:
CountDownLatch countDownLatchGroup = new CountDownLatch(sizeGroup);
for(int i=0;i<sizeGroup;i++){
ItemDumpThread thread = new ItemDumpThread(fineName,fileCount);
thread.start();
}
try {
countDownLatchGroup.await();
} catch (InterruptedException e) {
logger.error(e);
return false;
}
ok,没问题;
但是有一次,我不小心删除这段代码:
AtomicInteger fileCount;
String fileName;
public ItemDumpThread(
AtomicInteger fileCount,
String fileName,
){
this.fileName=fileName;
//this.fileCount=fileCount;删除了
}
public void run() {
logger.warn(destFile+"=>"+fileCount.incrementAndGet());//NPE...错误
}
这个错误,然后我主线程还继续等待,好像死锁一样。哎~~~
看来这种写法还是很危险~~~