What are the advantages of using an ExecutorService?

前端 未结 8 1064
孤城傲影
孤城傲影 2020-11-27 12:45

What is the advantage of using ExecutorService over running threads passing a Runnable into the Thread constructor?

8条回答
  •  半阙折子戏
    2020-11-27 13:34

    ExecutorService also gives access to FutureTask which will return to the calling class the results of a background task once completed. In the case of implementing Callable

    public class TaskOne implements Callable {
    
    @Override
    public String call() throws Exception {
        String message = "Task One here. . .";
        return message;
        }
    }
    
    public class TaskTwo implements Callable {
    
    @Override
    public String call() throws Exception {
        String message = "Task Two here . . . ";
        return message;
        }
    }
    
    // from the calling class
    
    ExecutorService service = Executors.newFixedThreadPool(2);
        // set of Callable types
        Set>callables = new HashSet>();
        // add tasks to Set
        callables.add(new TaskOne());
        callables.add(new TaskTwo());
        // list of Future types stores the result of invokeAll()
        List>futures = service.invokeAll(callables);
        // iterate through the list and print results from get();
        for(Futurefuture : futures) {
            System.out.println(future.get());
        }
    

提交回复
热议问题