基于Java Callable接口實現線程代碼實例
實現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'); }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
