submit和execute,以及区别
submit
submit方式适用于任务有返回结果
方法名 | 返回值类型 | 描述 |
---|---|---|
submit(Runnale) | Future<?> | 提交Runnable任务 |
submit(Runnable,T) | Future<?> | 提交Runnable任务并指定执行结果 |
submit(Callable) | Future<?> | 提交Callable任务 |
他们的返回值结果都是Future对象里面,并且都带有泛型。
我们来看下Future对象;
方法名 | 描述 |
---|---|
resultNow() | 立刻获取任务执行的结果 |
exceptionNow() | 立刻返回任务抛出的异常 |
get(long, TimeUnit) | 根据设定时间延时返回结果 |
get() | |
cancel(boolean) | 取消任务 |
state() |
代码示例
ResultTask.java
class ResultTask implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName());}
}
submit(Runable)
public class Test2 {public static void main(String[] args) {//创建任务Task task = new Task();//创建线程池ExecutorService executor = Executors.newSingleThreadExecutor();try {//提交任务Future<?> future = executor.submit(task);//打印返回结果System.out.println(future.get());}catch (InterruptedException | ExecutionException e){e.printStackTrace();}finally {//关闭线程池executor.shutdown();}}
}
执行结果,没有返回值,输出null
submit(Runnable,T)
public class Test2 {public static void main(String[] args) {//创建任务Task task = new Task();//创建线程池ExecutorService executor = Executors.newSingleThreadExecutor();try {//提交任务Future<String> future = executor.submit(task,"ok");//打印返回结果System.out.println(future.get());}catch (InterruptedException | ExecutionException e){e.printStackTrace();}finally {//关闭线程池executor.shutdown();}}
}
执行结果,输出任务指定的返回结果
submit(Callable)
package com.javaclimb;import java.util.concurrent.*;public class Test2 {public static void main(String[] args) {//创建任务ResultTask task = new ResultTask();//创建线程池ExecutorService executor = Executors.newSingleThreadExecutor();try {//提交任务Future<Integer> future = executor.submit(task);//打印返回结果System.out.println(future.get());}catch (InterruptedException | ExecutionException e){e.printStackTrace();}finally {//关闭线程池executor.shutdown();}}
}class ResultTask implements Callable<Integer> {@Overridepublic Integer call() throws Exception {return 1+1;}
}
执行结果:正常输出任务返回结果
execute
execute适用于任务没有返回结果的时候
package com.javaclimb;import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;public class Test1 {public static void main(String[] args) {//创建任务Task task = new Task();//创建线程池ExecutorService executor = Executors.newSingleThreadExecutor();//提交任务executor.execute(task);//关闭线程池executor.shutdown();}
}class Task implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName());}
}
执行结果,没有任何返回结果。
execute和submit的区别总结
execute | submit | |
---|---|---|
位置 | interface Executor | interface ExecutorService |
提交任务类别 | Runnable | Runable , Callable |
返回值类型 | void | Future<?> |