实现自定义Executor

时间:2017-10-18 20:00:29

标签: multithreading future executorservice completion-service

在下面的示例中,如果我在不使用ExecutorImpl的情况下实施Thread,则会阻止taskCompletionService.submit,即使它返回Future。 是否可以阻止submit,但不能在Thread中使用ExecutorImpl

class ExecutorServiceTest {

    private static class ExecutorImpl implements Executor {
        public void execute(Runnable r) {
            final Thread t = new Thread(new Runnable() { 
                public void run() { 
                    r.run();
                }});
            t.start();

            //If used will block others.
            //r.run();
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        final Executor executor = new ExecutorImpl(); 
        final CompletionService<String> taskCompletionService = new ExecutorCompletionService<>(executor);

        int submittedTasks = 3;
        for(int i = 0; i < submittedTasks; i++) {
            final int j = i;
        //here it is blocked if ExecutorServiceIml doesn't utilize Thread
            taskCompletionService.submit(new Callable<String>() {
                public String call() throws Exception {
                    Thread.sleep((3 - j) * 1000);
                    return "callable:" + String.valueOf(j);
                }
            });
            System.out.println("Task " + String.valueOf(i) + " has been submitted...");
        }
        for(int tasksHandled=0; tasksHandled < submittedTasks; tasksHandled++) {
            try {
                final Future<String> result = taskCompletionService.take();

                String l = result.get();
                System.out.println("Task has completed - result: " + l);

            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

0 个答案:

没有答案