作者Sofya (千野羽)
看板java
标题[问题] Java Synchronized 请益
时间Tue Apr 26 20:24:52 2011
向各位前辈请教一个Synchronized用法的问题
我的程式读取一个档案,将档案内每一行资料个别用一个Thread处理
一次最多用10个thread,并用一个Thread counter去记录目前已经开了几个Thread出去
每读取档案的一行资料,先检查Thread counter是否已经开满了Thread
如果满了就等待0.1秒再继续检查
开出来的Thread在执行完毕後会将 Thread 数目从Thread counter删去
--------------------部分程式码----------------
while ((strLine = br.readLine()) != null) {
while(((Integer)threadCount.get("thread")).intValue()>=10){
Thread.sleep(100); //检查thread是否已经超过10条,超过的话sleep 0.1秒再检查
}
synchronized(threadCount){ //开新的thread
int count = ((Integer)threadCount.get("thread")).intValue();
threadCount.put("thread", new Integer(count+1));
ProcessChartTasker charttasker = new ProcessChartTasker(threadCount);
Thread thread = new Thread(charttasker);
thread.start();
}
}
ProcessChartTasker中,程式执行完毕後会执行下列程式码将Thread数回收
synchronized(this.threadCount){
int count = ((Integer)this.threadCount.get("thread")).intValue();
this.threadCount.put("thread",new Integer(count-1));
}
目前测试起来在某些状况下,同一Thread好像不会完全开出10条,甚至当将Thread的数量加大到30时
同时间却可能只有12~14左右的Thread在执行,甚至要等原本开出来的Thread都执行完毕,才会继续
开新的Thread
小弟猜想是不是因为在主Thread中synchronized(threadCount),而sub-thread在结束时也会synchronized(this.threadCount)
导致当sub-thread数量增加时,主thread因为抢不到threadCount而无法开出新的Thread?
当其他sub-thread synchronized(this.threadCount)时,在主Thread中检察Thread Count数量的方法是否会无法取得Thread count数量?
又或是有比较好的检查机制?烦请各位前辈赐教,谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 111.251.197.148
1F:→ adrianshum:建议你直接用 ThreadPoolExecutor 04/30 00:47
2F:→ Sofya:感谢建议~~!! 05/05 06:51