基于Java Callable接口實現(xiàn)線程代碼實例
實現(xiàn)Callable接口(jdk8新特性)
可以獲得線程的返回值
*前兩種方式?jīng)]有返回值,因為run方法返回void
創(chuàng)建一個未來任務(wù)類對象 Futrue task = new Future(Callable<>);重寫call()方法 可以使用匿名內(nèi)部類方式
task.get()方法獲取線程返回結(jié)果
get方法執(zhí)行會導(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'); }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
