创建线程的三种方式

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单继承决定)。
注:一般推荐采用实现接口的方式来创建多线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值