1
我正在寻找只执行一个线程的特定操作集。 但是,我无法让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的情况下工作
上面的错字。 map.put(“WORKER”,thread); – qwerty
“我想知道为什么执行者在案件#2中不工作”您能详细说明吗? – bradimus
testCached()不会打印出“Ran”,表示没有调用可调用函数 – qwerty