java創建線程

總共有三種方式,Thread類,Runnable接口,和Callable接口

 Callable

以下是使用callable接口的一個例子

public class Main {
    public static void main(String[] args) {
        Callable<Integer> call = new Callable<Integer>(){
            
            public Integer call(){
                System.out.println("call");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return 10;
            }
            
        };
        FutureTask<Integer> future = new FutureTask<Integer>(call);
        //FutureTask 可用於 閉鎖 類似於CountDownLatch的作用,在所有的線程沒有執行完成之後這裏是不會執行的
        Thread th = new Thread(future);
        th.start();
        try {
            int out  =future.get();
            System.out.println(out);
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
  • callable有返回值
  • future.get()必須等到線程執行完有返回值,纔開始執行
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章