乐趣区

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 方式启动的");
    }
}

运行结果如下:

接口 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();}
}

运行结果如下:

接口 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();
        }
    }
}

运行结果如下:

接口 Runnable 和接口 Callable 的区别

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