1、继承Thread类创建线程
2、实现Runnable接口创建线程
3、使用callable和Future创建线程
1、使用继承Thread类创建线程步骤
(1)定义Thread子类,重写该类的run()方法该方法的方法体就是线程需要完成的任务,run()方法也称为线程执行体
(2)创建Thread子类的实例,也就是创建了线程对象
(3)启动线程,即调用线程的start()方法
public class myThread extends Thread{
public void run(){
}
}
public class Main {
public static void main(String[] args){
new MyThread().start();//创建并启动线程
}
}
2、实现Runnable接口创建线程
(1)定义Runnable接口的实现类,一样要重写run()方法,这个run()方法和Thread中的run()方法一样是线程的执行体
(2)创建Runnable实现类的实例,并用这个实例作为Thread的target来创建Thread对象,这个Thread对象才是真正的线程对象
(3)通过调用线程对象的start()方法来启动线程
public class MyThread implements Runnable {//实现Runnable接口
public void run(){
//重写run方法
}
}
public class Main {
public static void main(String[] args){
//创建并启动线程
MyThread myThread=new MyThread();
Thread thread=new Thread(myThread);
thread().start();
//或者 new Thread(new MyThread()).start();
}
}
3、使用callable和Future创建线程:
(1)创建Callable接口的实现类,并实现call()方法,然后创建该实现类的实例(从java8开始可以直接使用Lambda表达式创建Callable对象)。
(2)使用FutureTask类来包装Callable对象,该FutureTask对象封装了Callable对象的call()方法的返回值
(3)使用FutureTask对象作为Thread对象的target创建并启动线程(因为FutureTask实现了Runnable接口)
(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
public class Main {
public static void main(String[] args){
MyThread3 th=new MyThread3();
//使用Lambda表达式创建Callable对象
//使用FutureTask类来包装Callable对象
FutureTask<Integer> future=new FutureTask<Integer>(
(Callable<Integer>)()->{
return 5;
}
);
new Thread(task,"有返回值的线程").start();//实质上还是以Callable对象来创建并启动线程
try{
System.out.println("子线程的返回值:"+future.get());//get()方法会阻塞,直到子线程执行结束才返回
}catch(Exception e){
ex.printStackTrace();
}
}
}
4、三种创建线程方法对比
实现Runnable和实现Callable接口的方式基本相同,后者执行call()方法有返回值,线程执行体run()方法无返回值,因此可以把两种方式归为一种方式与继承Thread类的方法之间的差别:
(1)线程只是实现Runnable 或实现Callable接口,还可以继承其他类。
(2)这种方式下,多个线程可以共享一个target对象,非常适合多线程处理同一份资源的情形。
(3)但是编程稍微复杂,如果需要访问当前线程,必须调用Thread.currentThread()方法。
(4)继承Thread类的线程类不能再继承其他父类(Java单继承决定)。
注:一般推荐采用实现接口的方式来创建多线程