共计 922 个字符,预计需要花费 3 分钟才能阅读完成。
类 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 的区别
- Callable 可以有返回值。
- 通过 FutureTask 包装成 Runnable,传递给 Thread,因为 FutureTask 是实现了 Runnable 接口。
正文完
发表至: java
2019-07-03