概述
在我们需要用到线程时,通常会有多种实现方式,但是总归只有一个创建方法,就是实例化一个Thread类,然后进行不同的实现。
线程的实现方式
方式一:继承Thread类
public class test1 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.run();
}
}
class MyThread extends Thread{
@Override
public void run() {
System.out.println("我是创建线程的方式一");
}
}
继承之后可以重写Thread的run方法,来实现让指定线程执行指定的业务逻辑,因为实现的是一个类,所以还是继承了Object类,调用start()方法。
方式二:实现Runable接口
public class test2 {
public static void main(String[] args) {
MyThread02 thread = new MyThread02();
thread.run();
}
}
class MyThread02 implements Runnable{
@Override
public void run() {
System.out.println("我是线程创建方式二");
}
}
我们可以通过lambda表达式的方式来实现对run()方法的重写,简化代码运行逻辑,调用线程的run方法执行。
方式三:实现Callable接口
import java.util.concurrent.Callable;
public class test3 {
public static void main(String[] args) throws Exception {
MyThread3 myThread3 = new MyThread3();
myThread3.call();
}
}
class MyThread3 implements Callable{
@Override
public Object call() throws Exception {
System.out.println("我是创建线程的方式三");
return null;
}
}
Callable接口实现的call方法会有一个返回值,调用线程的call方法执行。