1

在下面的示例中,如果我在ExecutorImpl不使用的情况下实现Thread,则taskCompletionService.submit即使它返回,也会被阻止Future。是否可以不阻止submit但不使用Threadin 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();
            }
        }
    }
}
4

0 回答 0