adongsha 2018-10-11 11:57 采纳率: 0%
浏览 5201
已结题

ThreadPoolExecutor添加线程不执行,为什么

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

public class MyBlockingQueue implements Runnable {

BlockingQueue<String> queue;

private int index;

public MyBlockingQueue(BlockingQueue<String> queue, int index) {
    this.queue = queue;
    this.index = index;
}

@Override
public void run() {
    try {
        queue.put(String.valueOf(this.index));
        System.out.println("{" + this.index + "} in queue!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String args[]) {
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(3);

    ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("aaa-%s").build();
    ExecutorService pool = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), factory, new ThreadPoolExecutor.AbortPolicy());

    for (int i = 0; i < 10; i++) {
        pool.submit(new MyBlockingQueue(queue, i));
    }

  //为什么这里的线程不执行呢?
    pool.submit(() -> {
        try {
            while (true) {
                System.out.println("=======" + queue.size());
                if (queue.isEmpty()) {
                    break;
                }
                String str = queue.take();
                System.out.println(str + " has take!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

    pool.shutdown();
}

}

  • 写回答

1条回答 默认 最新

  • 大川里的小川人 2018-10-11 13:18
    关注

    首先想说一下,其中的问题,阻塞队列和工厂模式OK,
    在创建线程池的时候并不建议使用ExecutorService 中的构造函数,而是使用Executors里面提供的四种静态方法,很多的参数配置已经写好。

    其次,给线程池submit的应该是线程,而不是阻塞队列,你那里submit的是阻塞队列噢,循环体里面你可以写一个自己的类
    比如(class MyThread extends Thread),再写一个print,sleep一下,就可以看到线程池的执行啦。

    https://blog.csdn.net/whandwho/article/details/82931798 这个博客下方第八点

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料