java创建线程有哪几种方式
我们熟悉的最多见的
一、继承Thread类
总结:这里重写的是run()方法,不是start()方法,因为java是单继承类,占用了继承的名额,后面如果在有需要继承的类,不方便扩展。
其实看底层源码会发现,Thread类也是实现了runnable,所以更加推荐使用第二种方式创建线程
二、实现Runnable接口
总结:这里用的还是Threa类,但是因为java可以多继承,后续在扩展方便,也是我们现在最常用的创建线程的方式。
拓展:
简化代码我们可以使用匿名内部类的方式编写
public class MuJieThread{
public static void main(String[] args) {
Thread thread=new Thread(new Runnable(){
public void run(){
System.out.println("Mujie Hello");
}
});
thread.start();
}
}
或者利用java8的新特性lambda表达式
public class MuJieThread{
public static void main(String[] args) {
Thread thread=new Thread(()->{
System.out.println("MUjie Hello");
});
thread.start();
}
}
三、实现Callable类
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MuJieThread implements Callable<String> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask=new FutureTask<>(new MuJieThread());
Thread thread=new Thread(futureTask);
thread.start();
String result =futureTask.get();
System.out.println(result);
}
@Override
public String call() throws Exception {
return "Mujie Hello";
}
}
注意:这里不是实现run()方法,是call()方法,需要使用Thread+FutureTask配合,这种方式支持拿到异步执行任务的结果。
知识点:FutureTask的底层其实也是实现了Runnable类。
这里说一下,Java类是单继承,但是接口是可以多继承的。
四、利用线程池创建
import java.util.concurrent.*;
public class MuJieThread implements Runnable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService= Executors.newFixedThreadPool(10);
executorService.execute(new MuJieThread());
}
@Override
public void run() {
System.out.println("Mujie Hello");
}
}
这里实现Callable接口或者Runnable接口都可以。
其实上述四种方法都是围绕Runnable的。
总结:创建线程有四种方法,一、继承Thread类;二、实现Runnable接口;三、实现Callable接口;四、利用线程池创建
拓展:java类是单继承,接口可以多继承。