簡體   English   中英

如果我們在 Java 多線程中傳遞 executorService 執行調用中的線程會發生什么

[英]what happens if we pass threads in executorService execute call in Java multithreading

看這兩個例子:

示例 1

public static void main(String[] args) throws InterruptedException {

ExecutorService executorService = Executors.newCachedThreadPool();
        
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //work
                for (int i = 0 ; i < 5 ; i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        executorService.execute(thread1);
        executeService.shutdown();
}

例 2

public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                //work
                for (int i = 0 ; i < 5 ; i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        executeService.shutdown();
    }

兩種情況下的結果都相同,但我的一個來自 StackOverflow 的朋友alexei-kaigorodov在這個問題中)在評論中說

“executorService 是 treads 的替代品。將線程放在 executorService 中是沒有意義的。首先,創建 Runnable,然后將其作為參數放入線程並啟動該線程,或者將該 runnable 提交給 executorService。”

我希望我的問題很清楚,所以請告訴我將 runnable 傳遞給 ExecuteService 與將線程傳遞給 ExecutableService 的區別。

Thread implements Runnable ,因此執行器服務會將其作為簡單的Runnable接受,從而調用Thread.run()方法。

這意味着Thread本身永遠不會啟動,除非您自己調用它的start()方法,在這種情況下,結果是 def.netely undefined。

所以你可以說這些片段的行為是一樣的,你只是將一個Runnable傳遞給ExecutorService然后通過調用Runnable.run()方法來執行它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM