创建线程的三种方式

继承Thread的方式
代码如下:

[Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

public class MyThread extends Thread{//继承Thread类

     //重写run方法

  public void run(){

  }

}

public class Test{

  public static void main(String[] args){

    new MyThread().start();//创建并启动线程

  }

}

2 实现Runnable接口的方式
代码如下:

[Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

public class MyThread2 implements Runnable {//实现Runnable接口

 //重写run方法

  public void run(){

  }

}

public class Test{

  public static void main(String[] args){

    //创建并启动线程

    MyThread2 myThread=new MyThread2();

    Thread thread=new Thread(myThread);

    thread().start();

  }

}

3 使用Callable和Future创建线程
代码如下:

[Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

public class Test{

  public static void main(String[] args){

   MyThread3 th=new MyThread3();

   FutureTask<Integer> future=new FutureTask<Integer>(

    (Callable<Integer>)()->{

      return 10;

    }

    );

   new Thread(task,"线程1").start();//实质上还是以Callable对象来创建并启动线程

    try{

    System.out.println("返回值:"+future.get());//get方法会阻塞,直到子线程执行结束才返回

    }catch(Exception e){

    ex.printStackTrace();

   }

  }

}

三种方式的区别:
实现Runnable和实现Callable接口的方式道理相同,不过是call()方法有返回值,后者run()方法无返回值,因此可以把这两种方式归为一种这种方式并与继承Thread类的方法对比:
1、线程只是实现Runnable或实现Callable接口,还可以继承其他类。
2、多个线程可以共享一个target对象,非常适合多线程处理同一份资源的情形。
3、如果需要访问当前线程,必须调用Thread.currentThread()方法。
4、继承Thread类的线程类不能再继承其他父类,有局限性(Java单继承)。

评论

暂无评论