Java中有三种线程创建方式,分别为实现 Runnable接口的run方法 ,继承Thread类并重写run的方法,使用FutureTask方式 。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo {
/**
* 通过继承Thread类创建线程;
* 缺点:java不支持多继承
*/
static class MyThread extends Thread{
@Override
public void run() {
System.out.println("hello word");
}
}
/**
* 通过实现Runnable接口创建线程
*/
static class MyRunable implements Runnable{
@Override
public void run() {
System.out.println("hello word");
}
}
/**
* 通过实现Callable接口创建线程,使用FutureTask方式
*/
static class MyCallable implements Callable<String> {
@Override
public String call() {
return "hello word";
}
}
public static void main(String[] args) {
new MyThread().start();
new Thread(new MyRunable()).start();
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
new Thread(futureTask).start();
try {
String s = futureTask.get();//等待任务执行完成并返回结果
System.out.println(s);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}