2017-07-03 92 views
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的情况下工作

+0

上面的错字。 map.put(“WORKER”,thread); – qwerty

+0

“我想知道为什么执行者在案件#2中不工作”您能详细说明吗? – bradimus

+0

testCached()不会打印出“Ran”,表示没有调用可调用函数 – qwerty

回答

1

你的线程没有Runable来调用可调用对象。此代码适用于我

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