java併發編程學習之三種線程啓動方式

類Thread

public class ThreadDemo extends Thread {
    public static void main(String[] args) {
        ThreadDemo thread = new ThreadDemo();
        thread.start();
    }

    @Override
    public void run() {
        System.out.println("這是Thread方式啓動的");
    }
}

運行結果以下:
clipboard.pngide

接口Runnable

public class RunnableDemo implements Runnable {
    @Override
    public void run() {
        System.out.println("這是Runnable方式啓動的");
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new RunnableDemo());
        thread.start();
    }
}

運行結果以下:
clipboard.pngspa

接口Callable

public class CallableDemo implements Callable {
    @Override
    public String call() throws Exception {
        return "Callable";
    }
    public static void main(String[] args) {
        FutureTask<String> futureTask = new FutureTask(new CallableDemo());
        Thread thread = new Thread(futureTask);
        thread.start();
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

運行結果以下:
clipboard.pngcode

接口Runnable和接口Callable的區別

  1. Callable能夠有返回值。
  2. 經過FutureTask包裝成Runnable,傳遞給Thread,由於FutureTask是實現了Runnable接口。
相關文章
相關標籤/搜索