簡體   English   中英

Java ThreadFactory:為什么一個使用作品但其他不使用?

[英]Java ThreadFactory: Why does one use of works but other doesn't?

在下面的程序中,代碼在嘗試在方法second()Future執行get()時掛起! 這是為什么? 兩個執行程序服務之間的唯一區別是它們使用的ThreadFactory 如果我使用newSingleThreadExecutornewFixedThreadPool並且計數為1則newFixedThreadPool

package me.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

public class ExecutorServiceTest {
    ThreadFactory tf1 = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            t.setName("tf1-thread");
            return t;
        }
    };
    ThreadFactory tf2 = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread("tf2-thread");
            t.setDaemon(true);
            return t;
        }
    };
    ExecutorService service1 = Executors.newSingleThreadExecutor(tf1);
    ExecutorService service2 = Executors.newSingleThreadExecutor(tf2);
    Callable<Integer> callable = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return 0;
        }
    };

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorServiceTest executorTest = new ExecutorServiceTest();
        executorTest.first(); // this returns
        executorTest.second(); // this hangs
        System.exit(0);
    }

    void first() throws ExecutionException, InterruptedException {
        Future<Integer> future = service1.submit(callable);
        int result = future.get();
        System.out.println("result=" + result);
    }
    void second() throws ExecutionException, InterruptedException {
        Future<Integer> future = service2.submit(callable);
        int result = future.get();
        System.out.println("result=" + result);
    }
}

您的第一個工廠創建一個運行指定的runnable的線程:

Thread t = Executors.defaultThreadFactory().newThread(r);

而在你的第二個工廠,你只是忘了為創建的線程提供runnable:

Thread t = new Thread("tf2-thread");

因此,在第二種情況下,runnable永遠不會運行,因此未來永遠不會獲得價值。

將第二種情況下的線程創建更改為

Thread t = new Thread(r, "tf2-thread");

暫無
暫無

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

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