Runnable Callable Future FutrueTask ExecutorService的关系

 

public interface ExecutorService extends Executor {...}

ExecutorService#submit三个重载方法,之前一直没注意,今天仔细以研究,还是有好些知识点的

1.第一个就不说了

<T> Future<T> submit(Callable<T> task);

 

2.返回的future#get会阻塞,得到的结果就是result

<T> Future<T> submit(Runnable task, T result);

 

3.future#get也是会阻塞的,只是返回的结果是null

Future<?> submit(Runnable task);

 

a.FutureTask是Future的唯一实现

public class FutureTask<V> implements RunnableFuture<V> {...}

public interface RunnableFuture<V> extends Runnable, Future<V> {...}

 

code demo

ExecutorService executor = Executors.newSingleThreadExecutor();

Future future = executor.submit(new Runnable() {
    public void run() {
        System.out.println("run");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
});
System.out.println(future.get());

final List<String> list = Lists.newArrayList("a", "b");
Future future2 = executor.submit(new Runnable() {
    public void run() {
        list.add("c");
        System.out.println("run with result");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}, list);
System.out.println(future2.get());

executor.shutdown();

 
执行结果

run
null
run with result
[a, b, c]

 

 

你可能感兴趣的:(java)