简体   繁体   English

为什么FixedThreadPool无法正常工作

[英]Why FixedThreadPool not working properly

Here's my following code: 这是我的以下代码:

    ExecutorService executor = Executors.newFixedThreadPool(5);

    executor.submit(new Runnable() {
        public void run() {
            for (int i = 0; i < 5; i++) {
              System.out.println("Start"+"  "+Thread.currentThread().getName());
              try {
                Thread.sleep(100);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              System.out.println("End!"+"  "+Thread.currentThread().getName());
            }
        }
    });

    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.SECONDS);

Here's my output: 这是我的输出:

    Start  pool-1-thread-1
    End!  pool-1-thread-1
    Start  pool-1-thread-1
    End!  pool-1-thread-1
    Start  pool-1-thread-1
    End!  pool-1-thread-1
    Start  pool-1-thread-1
    End!  pool-1-thread-1
    Start  pool-1-thread-1
    End!  pool-1-thread-1

My understanding is that in my code there're 5 threads in FixedThreadPool . 我的理解是,在我的代码中, FixedThreadPool5线程。 So when I run my code, it's supposed to output all 5 threads, right? 因此,当我运行代码时,应该输出所有5线程,对吗? Or Am I misunderstanding something? 还是我误会了什么?

In my output thread-1 starts and end everytime but isn't it supposed to output all 5 threads when it loops in for loop? 在我的输出thread-1每次都开始和结束,但是当它循环for循环时,它不是应该输出所有5线程吗? Cause if only 1 thread is doing the task then why do we even need 5 threads ? 原因是如果只有1个thread在执行task那为什么还要5个threads呢? Is there any way all 5 threads can output on the console?(I'm a newbie) 所有5线程都可以在控制台上输出任何方式吗?(我是新手)

You are posting only one Runnable so your ExecutorService runs one task. 您只发布了一个Runnable因此您的ExecutorService运行了一项任务。 It will use only one thread. 它只会使用一个线程。 To use multiple threads you must call submit multiple times or you can call invokeAll with a Collection of runnables. 要使用多个线程,您必须多次调用submit ,或者可以使用可运行对象的Collection调用invokeAll

EDIT 编辑

Something like this: 像这样:

public void test() {
    int numberOfThreads = 5;
    ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
    for(int i=0; i<numberOfThreads; i++){
        executorService.submit(createRunnable());
    }
}

private Runnable createRunnable() {
    return new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println("Start" + "  " + Thread.currentThread().getName());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("End!" + "  " + Thread.currentThread().getName());
            }
        }
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM