国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

基于Java Callable接口實現線程代碼實例

瀏覽:2日期:2022-08-26 15:39:04

實現Callable接口(jdk8新特性)

可以獲得線程的返回值

*前兩種方式沒有返回值,因為run方法返回void

創建一個未來任務類對象 Futrue task = new Future(Callable<>);重寫call()方法 可以使用匿名內部類方式

task.get()方法獲取線程返回結果

get方法執行會導致當前方法阻塞 效率較低

代碼如下

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'); }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 南城县| 唐山市| 安溪县| 景德镇市| 固原市| 柳林县| 岳池县| 工布江达县| 衡阳市| 泾源县| 蒲城县| 宿松县| 新余市| 延津县| 太康县| 鱼台县| 崇左市| 河南省| 高密市| 连南| 彭泽县| 柞水县| 江陵县| 五寨县| 麻栗坡县| 腾冲县| 灵台县| 商城县| 彭州市| 昭苏县| 莫力| 海林市| 禄劝| 小金县| 邻水| 清流县| 磴口县| 美姑县| 张家口市| 宁陕县| 梅河口市|