类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接口。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。