Java并发基础(18):ExecutorService中submit方法详解

文章聚焦Java线程池的submit方法,该方法接收Runnable或Callable对象为参数,返回Future对象。其返回值类型取决于任务中call方法的返回类型,如call返回Integer,submit就返回Future<Integer>,需用对应类型引用返回值。

目录

1 submit()


1 submit()

submit( ):该方法接收Runnable或Callable对象作为输入参数(该方法输入参数请参考上篇文章java线程池任务提交(Runnable、Callable、FutureTask), 这篇文章主要讲submit方法的返回值以及返回值的使用),返回一个Future对象。submit方法提交的任务中的call方法如果返回Integer,那么submit方法就返回Future<Integer>;如果call方法返回Float,那么submit方法就返回Future<Float>;call方法返回的List<Integer>,那么submit方法就返回Future<List<Integer>>,以此类推。具体返回的是哪一种,那么就使用对应类型的引用来引用submit方法的返回值。例如:
 

public class Thread implements Runnable {}

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

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
public interface Executor {
    void execute(Runnable command);
}

public interface ExecutorService extends Executor {
    void shutdown();
    List<Runnable> shutdownNow();
    boolean isShutdown();

    boolean isTerminated();

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

public abstract class AbstractExecutorService implements ExecutorService {
    public Future<?> submit(Runnable task) {
        ...
    }
    public <T> Future<T> submit(Runnable task, T result) {
       ...
    }
    public <T> Future<T> submit(Callable<T> task) {
        ...
    }
}

public class ThreadPoolExecutor extends AbstractExecutorService {
     public void execute(Runnable command) {
         ...  
     }
     public void shutdown() {
        ...
     }
     public boolean isShutdown() {
        ...
    }
    public boolean isTerminating() {
        ...
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值