簡體   English   中英

為什么FixedThreadPool無法正常工作

[英]Why FixedThreadPool not working properly

這是我的以下代碼:

    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);

這是我的輸出:

    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

我的理解是,在我的代碼中, FixedThreadPool5線程。 因此,當我運行代碼時,應該輸出所有5線程,對嗎? 還是我誤會了什么?

在我的輸出thread-1每次都開始和結束,但是當它循環for循環時,它不是應該輸出所有5線程嗎? 原因是如果只有1個thread在執行task那為什么還要5個threads呢? 所有5線程都可以在控制台上輸出任何方式嗎?(我是新手)

您只發布了一個Runnable因此您的ExecutorService運行了一項任務。 它只會使用一個線程。 要使用多個線程,您必須多次調用submit ,或者可以使用可運行對象的Collection調用invokeAll

編輯

像這樣:

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