2017-07-03 78 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); 
    }