2015-06-05 161 views
0

如何在M線程中運行我的任務N次?例如,我有一些任務在不同線程中運行任務

public static Runnable createTask() { 
    Runnable runnable = new Runnable() { 
    @Override 
    public void run() {    
     System.out.println("simple task"); 
    } 
    }; 
return runnable; 
} 

我需要運行此任務N次並將工作分爲M線程。

+1

使用'ExecutorService' - 特別https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int%29 – user3707125

+0

謝謝!有用! – user3504091

回答

1

你在這裏。如果您想讓相同的任務運行「N」時間,則創建「N」Callable實例的相同任務,並將其添加到CallableList中,您將傳遞給invokeAll方法。

 try { 
     List<Callable<Object>> callableList = new ArrayList<Callable<Object>>(); 
     callableList.add(null); /*Add instance of Callable*/ 
     callableList.add(null); /*Add instance of Callable*/ 
     callableList.add(null); /*Add instance of Callable*/ 

     //Specify how many threads you want or need to operate. Read other methods of Executors which return different instances of ExecutorService 
     final ExecutorService service = Executors.newFixedThreadPool(3); 

     //This will invoke all your N tasks in specified M threads ... 
     service.invokeAll(callableList); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
相關問題