1.继承Thread,重写run()
public static void main(String[] args){
MyThread t = new MyThread();
t.run();
}
private static class MyThread extends Thread{
@Override
public void run(){
//do...
}
}
2.实现Runnable接口,重写run()
public static void main(String[] args){
MyThread t = new MyThread();
t.run();
}
private static class MyThread implements Runnable{
@Override
public void run(){
//do...
}
}
3.实现Callable接口,有返回值,支持泛型
public static void main(String[] args) throws Exception {
MyThread t = new MyThread();
System.out.println(t.call());
}
private static class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception{
//do...
return 1;
}
}
一般结合Future使用:
Future是一个支持泛型的接口,唯一的实现类是FutureTask,用来在多线程情况下获得线程异步执行的结果。(常在线程池中使用)
FutureTask实现了RunnableFuture接口,而RunnableFuture接口继承自Runnable和Future接口。
FutureTask的两种构造方式:
public FutureTask(Callable<V> callable){...}
public FutureTask(Runnable runnable,V result){...}
向线程池提交带有返回结果的任务:
<T> Future<T> submit(Callable<T> task)
<T> Future<T> submit(Runnable task,T result)
再通过Future接口提供的get()方法获取结果。
例如:
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task(); //Task类实现了Callable接口
Future<Integer> result = executor.submit(task);
int res = result.get();
private class Task implements Callable<Integer>{
}