具有缓存线程

时间:2017-07-03 14:04:44

标签: java

我希望仅使用一个线程执行一组特定的操作。 但是,我无法让Executors.newSingleThreadExecutor使用地图中的缓存线程。

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class ThreadTest {
    private final Callable<Boolean> task = new Callable() {
        @Override
        public Boolean call() {
            System.out.println("Ran");
            return Boolean.TRUE;
        }
    };

    //this prints the Callable output "Ran"
    @Test
    public void testVanilla() throws InterruptedException {
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.submit(task);
        Thread.sleep(10);
    }

    //this does not print the Callable output "Ran"
    @Test
    public void testCached() throws InterruptedException {
        Map<String, Thread> map = new HashMap<>();
        Thread thread = new Thread("WORKER");
        thread.setDaemon(false);
        map.put("uniq", thread);
        ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return map.get("WORKER");
            }
        });

        service.submit(task);
        Thread.sleep(10);
    }
}

有什么明显的错误吗?我想知道为什么执行者在#2

的情况下不起作用

1 个答案:

答案 0 :(得分:1)

你的线程没有Runable来调用callable。本规范适用于我

    @Test
    public void testCached() throws InterruptedException {
        Map<String, Thread> map = new HashMap<>();
        ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {

                if (!map.containsKey("WORKER")) {
                    Thread thread = new Thread(r, "WORKER");
                    thread.setDaemon(false);
                    map.put("WORKER", thread);
                }

                return map.get("WORKER");
            }
        });

        service.submit(task);
        Thread.sleep(10);
    }