基于Java Callable接口實(shí)現(xiàn)線程代碼實(shí)例
實(shí)現(xiàn)Callable接口(jdk8新特性)
可以獲得線程的返回值
*前兩種方式?jīng)]有返回值,因?yàn)閞un方法返回void
創(chuàng)建一個(gè)未來任務(wù)類對(duì)象 Futrue task = new Future(Callable<>);重寫call()方法 可以使用匿名內(nèi)部類方式
task.get()方法獲取線程返回結(jié)果
get方法執(zhí)行會(huì)導(dǎo)致當(dāng)前方法阻塞 效率較低
代碼如下
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;public class Test_13 { public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + 'begin'); FutureTask task = new FutureTask(new Callable() { @Override public Object call() throws Exception {System.out.println(Thread.currentThread().getName() + 'start');Thread.sleep(1000 * 5);int a = 100;int b = 200;System.out.println(Thread.currentThread().getName() + 'over');return a + b; } }); Thread thread = new Thread(task); thread.start(); try { System.out.println(task.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + 'end'); }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算2. 詳解idea中web.xml默認(rèn)版本問題解決3. JSP頁(yè)面實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能4. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法5. jsp EL表達(dá)式詳解6. asp知識(shí)整理筆記4(問答模式)7. ASP實(shí)現(xiàn)加法驗(yàn)證碼8. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)9. java 優(yōu)雅關(guān)閉線程池的方案10. Python matplotlib 繪制雙Y軸曲線圖的示例代碼
