18455783050 2019-12-05 14:38 采纳率: 0%
浏览 219
已结题

两个问题,1、是线程一直没有结束,2、System.out.println("--------------dataNum = " + dataNum);这句输出的值也不争确,请指教.

public class T05_ThreadPool {
public static void main(String[] args) throws InterruptedException {
ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();
for (int i = 0; i < 10000; i++) {
queue.offer(i);
}
AtomicInteger dataNum = new AtomicInteger(0);
ExecutorService service = Executors.newFixedThreadPool(8); //execute submit
int queueSize = queue.size();
for (int i = 0; i < queueSize; i++) {
service.execute(new Runnable(){
@Verride
public void run(){
try{
if(!queue.isEmpty()){
System.out.println("-------" + queue.poll() + "-------");
TimeUnit.MILLISECONDS.sleep(500);
dataNum.addAndGet(1);
}else{
service.shutdown();
System.out.println("--------------dataNum = " + dataNum);
}

                    }catch(Exception e){
                        e.printStackTrace();
                        service.shutdown();
                }
            }
        });
    }

    System.out.println(service);
}

}

  • 写回答

2条回答 默认 最新

  • 轻点 别打脸 2019-12-05 16:16
    关注

    队列中一共一万个元素,你建立了一个线程池,8个线程,循环一万次也始终是这8个线程在处理,最后一个元素被某一个线程处理完后,队列虽然为空了,但你的for循环也完了,没有调用shutdown结束线程,多循环一次就可以了。
    输出结果不对,你在service.shutdown();前面加一个线程休眠,让执行中的线程执行完毕,结果自然就对了,线程shutdown是立即执行,即使有正在执行中的线程。
    若解决了你的疑问,望采纳,若还有疑问可以提出

    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示