基於Java Callable介面實現執行緒程式碼例項
阿新 • • 發佈:2020-08-21
實現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"); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。