實現 Runnable
接口的 run
方法java
Runnable runnable = () -> System.out.println("我是一個子線程");
與 Thread
相比,由於 Java 不支持多繼承,因此 Runnable
的優點在能夠多實現。ide
Thread thread = new Thread(() -> System.out.println("我是一個子線程")); thread.start();
class CallableDemo implements Callable<Integer> { @Override public Integer call() { int sum = 0; for (int i = 0; i < 100; i++) { System.out.println(i); sum += i; } return sum; } } public static void main(String[] args) { CallableDemo t = new CallableDemo(); FutureTask<Integer> ft = new FutureTask<>(t); new Thread(ft).start(); try { Integer sum = ft.get(); // 使用 get() 方法等待獲取返回值 System.out.println("sum = " + sum); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }