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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据