1

类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.png

接口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.png

接口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.png

接口Runnable和接口Callable的区别

  1. Callable可以有返回值。
  2. 通过FutureTask包装成Runnable,传递给Thread,因为FutureTask是实现了Runnable接口。

大军
847 声望183 粉丝

学而不思则罔,思而不学则殆