ConcurrentLinkedQueue<String> queue=null;
int times=10;
private void doLongTime(String a,long millis){
logger.info("开始工作:"+a);
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info("结束工作:"+a);
}
@Test
public void testSingle(){
List<String>list=new LinkedList<String>();
for(int i=0;i<times;i++){
list.add(String.valueOf(i));
}
queue=new ConcurrentLinkedQueue<String>(list);
long s=System.currentTimeMillis();
String temp="";
while((temp=queue.poll())!=null){
doLongTime(temp,1000);
}
long e=System.currentTimeMillis();
logger.info(String.valueOf((e-s))+"毫秒");
}
@Test
public void testMulti(){
List<String>list=new LinkedList<String>();
for(int i=0;i<times;i++){
list.add(String.valueOf(i));
}
queue=new ConcurrentLinkedQueue<String>(list);
long s=System.currentTimeMillis();
int threadPoolSize=10;
final CountDownLatch co = new CountDownLatch(threadPoolSize);
ExecutorService es = Executors.newFixedThreadPool(threadPoolSize);
// 执行任务
for (int i = 0; i < threadPoolSize; i++) {
es.execute(new doThead(co,queue));
}
// 等待执行完
try {
co.await();
} catch (InterruptedException e) {
System.out.println("线程计数器异常"+e);
} finally {
System.out.println("执行完");
}
long e=System.currentTimeMillis();
logger.info(String.valueOf((e-s))+"毫秒");
}
private class doThead implements Runnable{
private CountDownLatch c;
private ConcurrentLinkedQueue<String> q;
public doThead(CountDownLatch c,ConcurrentLinkedQueue<String> q) {
this.c = c;
this.q = q;
}
@Override
public void run() {
String temp="";
while((temp=q.poll())!=null){
doLongTime(temp,1000);
}
c.countDown();
}
}