實現Callable接口。帶返回值的線程


callable

1.任務結束后可以提供一個返回值

2.其中的call方法可以拋出異常

3.運行callable可以拿到一個Future對象,Future對象表示異步計算的結果,他提供了檢查計算是否完成的方法。

實現Callable接口

public class Main implements Callable{
    int i;
    @Override
    public Object call() throws Exception {
        String str=null;
        for (i=0;i<100;i++){
            str=Thread.currentThread().getName()+"--"+i;
            System.out.println(str);
        }
        return str;
    }
}

測試

public class Client {
    public static void main(String[] args) {
        ExecutorService threadPool= Executors.newSingleThreadExecutor();
        Future<String> future=threadPool.submit(new Main());
        System.out.println("----------");
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

線程結束后,future.get()方法會返回結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM