Callable接口
生活随笔
收集整理的這篇文章主要介紹了
Callable接口
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Runnable是執(zhí)行工作的獨(dú)立任務(wù),但是它不返回任何值。如果希望任務(wù)在完成的同時(shí)能夠返回一個(gè)值,可以通過實(shí)現(xiàn)Callable接口。在JDK5.0中引入的Callable接口是一種具有類型參數(shù)的泛型,它的類型參數(shù)表示從方法call中返回的值的類型。
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask;public class Demo05 {public static void main(String[] args) throws ExecutionException, InterruptedException {Callable<Integer> callable = new Demo05Callable();FutureTask<Integer> task = new FutureTask<>(callable);Thread t1 = new Thread(task);t1.start();System.out.println("線程返回的值是:" + task.get());} }class Demo05Callable implements Callable<Integer>{@Overridepublic Integer call() throws Exception {System.out.println(Thread.currentThread().getName() + "調(diào)用了callable接口的實(shí)現(xiàn)類");int val = (int)(Math.random() * 10);System.out.println("準(zhǔn)備返回的值是:" + val);return val;} }?
總結(jié)
以上是生活随笔為你收集整理的Callable接口的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: synchronized同步方法
- 下一篇: mybatis整体架构