一文搞懂Runnable、Callable、Future、FutureTask及應(yīng)用
一般創(chuàng)建線程只有兩種方式,一種是繼承Thread,一種是實(shí)現(xiàn)Runnable接口。但是這兩種創(chuàng)建方式有一個(gè)致命的缺點(diǎn)就是沒(méi)有返回值,沒(méi)返回值就讓人很苦惱了啊。得用共享變量或者其他通信方式才能得到線程處理完的結(jié)果,就有點(diǎn)麻煩。
還有一般不提倡使用繼承Thread來(lái)創(chuàng)建線程方式,因?yàn)镴ava只有單繼承,不能繼承多個(gè)。但是Runnable是接口,所以可以讓你的實(shí)現(xiàn)類同時(shí)實(shí)現(xiàn)多個(gè)接口。而且之后要上線程池,如果之前你是用Runnable來(lái)實(shí)現(xiàn)的,那就可以直接傳入Runnable給線程池進(jìn)行管理了!
在Java1.5之后就有了Callable、Future。這二種可以提供線程執(zhí)行完的結(jié)果!
接下來(lái)簡(jiǎn)單介紹下Runnable、Callable 、Future、 FutureTask。
Runnable
Runnable 是一個(gè)接口,簡(jiǎn)單就一個(gè)方法,實(shí)現(xiàn)run方法,在run方法里面編寫你要執(zhí)行的代碼就行了,但是沒(méi)有任務(wù)返回接口,并且無(wú)法拋出異常。
public interface Runnable { public abstract void run(); }
簡(jiǎn)單應(yīng)用
Runnable runnable = new Runnable() { @Override public void run() { System.out.println("2333"); } }; Thread thread = new Thread(runnable); thread.start();
Callable
Callable也是一個(gè)接口,很簡(jiǎn)單就一個(gè)call方法,在call方法里面編寫你要執(zhí)行的代碼就行了,返回的就是執(zhí)行的結(jié)果了。和Runnable 差別就是它有返回的結(jié)果,并且可以拋出異常!一般配合ThreadPoolExecutor使用的。
public interface Callable<V> { V call() throws Exception; }
簡(jiǎn)單應(yīng)用,它不能直接配合Thread 使用。
Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { return "2333"; } }; ExecutorService executor = Executors.newFixedThreadPool(1); Future<String> result = executor.submit(callable); System.out.println(result.get());
Future
Future也是一個(gè)接口,它可以對(duì)具體的Runnable或者Callable任務(wù)進(jìn)行取消、判斷任務(wù)是否已取消、查詢?nèi)蝿?wù)是否完成、獲取任務(wù)結(jié)果。如果是Runnable的話返回的結(jié)果是null(下面會(huì)剖析為什么Runnable的任務(wù),F(xiàn)uture還能返回結(jié)果)。接口里面有以下幾個(gè)方法。注意兩個(gè)get方法都會(huì)阻塞當(dāng)前調(diào)用get的線程,直到返回結(jié)果或者超時(shí)才會(huì)喚醒當(dāng)前的線程。
public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); // 取消任務(wù) boolean isCancelled(); // 判斷任務(wù)是否已取消 boolean isDone(); // 判斷任務(wù)是否已結(jié)束 V get() throws InterruptedException, ExecutionException;// 獲得任務(wù)執(zhí)行結(jié)果 // 獲得任務(wù)執(zhí)行結(jié)果,支持超時(shí) V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
簡(jiǎn)單應(yīng)用
Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { return "2333"; } }; ExecutorService executor = Executors.newFixedThreadPool(1); Future<String> result = executor.submit(callable); result.cancel(true); System.out.println(result.isCancelled());
FutureTask
因?yàn)镕uture只是一個(gè)接口,所以是無(wú)法直接用來(lái)創(chuàng)建對(duì)象使用的,因此就有了下面的FutureTask。 FutureTask不是接口了,是個(gè)class。它實(shí)現(xiàn)了RunnableFuture接口 public class FutureTask<V> implements RunnableFuture<V>
而RunnableFuture接口又繼承了Runnable和Future public interface RunnableFuture<V> extends Runnable, Future<V>
因此它可以作為Runnable被線程執(zhí)行,又可以有Future的那些操作。它的兩個(gè)構(gòu)造器如下
FutureTask(Callable<V> callable); FutureTask(Runnable runnable, V result);
簡(jiǎn)單應(yīng)用
FutureTask<String> futureTask = new FutureTask<>(() -> "2333"); Thread T1 = new Thread(futureTask); T1.start(); String result = futureTask.get(); System.out.println(result);
線程池應(yīng)用
一般情況我們?cè)谟枚嗑€程的時(shí)候都會(huì)上線程池,而且一般我們使用ThreadPoolExecutor來(lái)創(chuàng)建線程池,我的上篇文章已經(jīng)講述了ThreadPoolExecutor,這里再補(bǔ)充一下submit用法。
Future<?> submit(Runnable task); // 提交 Runnable 任務(wù) <T> Future<T> submit(Callable<T> task); // 提交 Callable 任務(wù) <T> Future<T> submit(Runnable task, T result); // 提交 Runnable 任務(wù)及結(jié)果引用
也就是說(shuō)如果我們需要返回任務(wù)的執(zhí)行結(jié)果我們就得調(diào)用submit方法而不是execute。 submit也不神秘就是封裝了一下我們的任務(wù)再execute
public Future<?> submit(Runnable task) { if (task == null) throw new NullPointerException(); RunnableFuture<Void> ftask = newTaskFor(task, null); //轉(zhuǎn)成 RunnableFuture,傳的result是null execute(ftask); return ftask; } public <T> Future<T> submit(Runnable task, T result) { if (task == null) throw new NullPointerException(); RunnableFuture<T> ftask = newTaskFor(task, result); execute(ftask); return ftask; } public <T> Future<T> submit(Callable<T> task) { if (task == null) throw new NullPointerException(); RunnableFuture<T> ftask = newTaskFor(task); execute(ftask); return ftask; }
newTaskFor方法是new了一個(gè)FutureTask返回。 所以三個(gè)方法其實(shí)都是把task轉(zhuǎn)成FutureTask,如果task是Callable,就直接賦值。如果是Runnable 就轉(zhuǎn)為Callable再賦值
task是Callable的情況
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { return new FutureTask<T>(callable); } public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); this.callable = callable; this.state = NEW; }
task是Runnable 的情況
// 按順序看,層層調(diào)用 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { return new FutureTask<T>(runnable, value); } public FutureTask(Runnable runnable, V result) { this.callable = Executors.callable(runnable, result); //轉(zhuǎn) runnable 為 callable this.state = NEW; } // 以下為Executors中的方法 public static <T> Callable<T> callable(Runnable task, T result) { if (task == null) throw new NullPointerException(); return new RunnableAdapter<T>(task, result); } static final class RunnableAdapter<T> implements Callable<T> { //適配器 final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; } }
看了源碼就揭開(kāi)了神秘面紗了,就是因?yàn)镕uture需要返回結(jié)果,所以內(nèi)部task必須是Callable,如果task是Runnable 我就造個(gè)假,偷天換日,在Runnable 外面包個(gè)Callable馬甲,返回的結(jié)果在構(gòu)造時(shí)就寫好。
如果是調(diào)用Future<?> submit(Runnable task);
提交任務(wù),構(gòu)造的時(shí)候就直接是RunnableFuture<Void> ftask = newTaskFor(task, null);
直接塞了個(gè)null。所以調(diào)用Future.get時(shí),拿到的就是null。所以這樣有什么用呢?就只用能來(lái)判斷任務(wù)已經(jīng)執(zhí)行完畢,就類似于Thread.join。
這還有個(gè)<T> Future<T> submit(Runnable task, T result);
你可能會(huì)奇怪這有啥用啊,你傳入一個(gè)result,F(xiàn)uture.get的時(shí)候返回的不還是這個(gè)result嘛。是個(gè)沒(méi)錯(cuò),但是這樣用就行了!
class Task implements Runnable{ //定義task,傳入p Person p; Task(Person r){ // 通過(guò)構(gòu)造函數(shù)傳入 p this.p = p; } void run() { r.setSex("男"); // 可以修改p } } Person p = new Person(); p.setName("小明"); ExecutorService executor = Executors.newFixedThreadPool(1); Future<Result> future = executor.submit(new Task(p), p); Person person = future.get(); person.getSex();
這樣就可以得到修改后的結(jié)果了!
總結(jié)
綜上所述,知道了Runnable 和Callable 的區(qū)別,Callable 可以獲得任務(wù)結(jié)果和拋出異常,Runnable 沒(méi)結(jié)果沒(méi)異常拋出。
Future可以很容易的獲得異步執(zhí)行的結(jié)果,并且對(duì)任務(wù)進(jìn)行一些操控。并且get等待結(jié)果時(shí)會(huì)阻塞,所以當(dāng)任務(wù)之間有依賴關(guān)系的時(shí)候,一個(gè)任務(wù)依賴另一個(gè)任務(wù)的結(jié)果,可以用Future的get來(lái)等待依賴的任務(wù)完成的結(jié)果。
FutureTask 就是具體的實(shí)現(xiàn)類,有Runnable 的特性又有Future的特性,內(nèi)部包的是Callable ,當(dāng)然也有接受Runnable 的構(gòu)造器,只是會(huì)偷偷把Runnable 轉(zhuǎn)成Callable 來(lái)實(shí)現(xiàn)能返回結(jié)果的方法。
到此這篇關(guān)于一文搞懂Runnable、Callable、Future、FutureTask及應(yīng)用的文章就介紹到這了,更多相關(guān)Runnable Callable Future FutureTask內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
idea普通javaweb項(xiàng)目如何部署到tomcat(讀取web.xml文件)
這篇文章主要介紹了idea普通javaweb項(xiàng)目如何部署到tomcat(讀取web.xml文件),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08Java淺析代碼塊與構(gòu)造塊及靜態(tài)塊三者之間的關(guān)系
所謂代碼塊是指用"{}"括起來(lái)的一段代碼,根據(jù)其位置和聲明的不同,可以分為普通代碼塊、構(gòu)造塊、靜態(tài)塊、和同步代碼塊。如果在代碼塊前加上synchronized關(guān)鍵字,則此代碼塊就成為同步代碼塊2022-07-07帶你了解如何使用Spring基于ProxyFactoryBean創(chuàng)建AOP代理
這篇文章主要介紹了Spring基于ProxyFactoryBean創(chuàng)建AOP代理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-08-08Python實(shí)現(xiàn)filter函數(shù)實(shí)現(xiàn)字符串切分
這篇文章主要介紹了Python實(shí)現(xiàn)filter函數(shù)實(shí)現(xiàn)字符串切分,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03SpringCloud中的斷路器(Hystrix)和斷路器監(jiān)控(Dashboard)
本篇主要介紹的是SpringCloud中的斷路器(Hystrix)和斷路器指標(biāo)看板(Dashboard)的相關(guān)使用知識(shí),需要的朋友可以參考下2019-06-06Shiro在springboot中快速實(shí)現(xiàn)方法
Apache Shiro是一個(gè)Java的安全(權(quán)限)框架,可以容易的開(kāi)發(fā)出足夠好的應(yīng)用,既可以在JavaEE中使用,也可以在JavaSE中使用,這篇文章主要介紹了Shiro在springboot中快速實(shí)現(xiàn),需要的朋友可以參考下2023-02-02