好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java创建线程三种方式的优缺点

java创建 线程 主要有三种方式:继承thread类创建线程、实现runnable接口创建线程和实现callable和future创建线程。

继承thread类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

public class thread1 extends thread {

   @override

   public void run() {

     for ( int i = 0 ; i < 10 ; i++) {

       system.out.println(getname() + ": " + i);

     }

   }

   public static void main(string[] args) {

     for ( int i = 0 ; i < 10 ; i++) {

       system.out.println(thread.currentthread().getname() + ": " + i);

       if (i == 2 ) {

         new thread1().start();

         new thread1().start();

       }

     }

   }

}

实现runnable接口

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class thread2 implements runnable {

   @override

   public void run() {

     for ( int i = 0 ; i < 10 ; i++) {

       system.out.println(thread.currentthread().getname() + ": " + i);

     }

   }

   public static void main(string[] args) {

     for ( int i = 0 ; i < 10 ; i++) {

       system.out.println(thread.currentthread().getname() + ": " + i);

       if (i == 2 ) {

         thread2 thread2 = new thread2();

         new thread(thread2).start();

         new thread(thread2).start();

       }

     }

   }

}

实现callable接口

futuretask类包装callable对象时,封装了callable对象的call()方法的返回值。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

class thread3 implements callable {

   @override

   public integer call() throws exception {

     int i = 0 ;

     for (; i < 10 ; i++) {

       system.out.println(thread.currentthread().getname() + ": " + i);

     }

     return i;

   }

   public static void main(string[] args) {

     thread3 thread3 = new thread3();

     futuretask<integer> futuretask = new futuretask<integer>(thread3);

     for ( int i = 0 ; i < 10 ; i++) {

       system.out.println(thread.currentthread().getname() + " :" + i);

       if (i == 2 ) {

         new thread(futuretask, "有返回值的线程" ).start();

       }

     }

     try {

       system.out.println( "子线程返回值: " + futuretask.get());

     } catch (interruptedexception e) {

       e.printstacktrace();

     } catch (executionexception e) {

       e.printstacktrace();

     }

   }

}

三种方式优缺点

采用实现接口(runnable和callable)的方式,线程类还可以继承其他的类。实现接口的线程对象还可以用来创建多个线程,可以实现资源共享。缺点是不能使用this指针来获取线程的名字等。

采用继承thread类的方式,线程不能继承其他的类,但是thread类中有getname方法,因为可以直接使用this.getname()来获取当前线程的名字。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/sinat_28394909/article/details/84956184

查看更多关于Java创建线程三种方式的优缺点的详细内容...

  阅读:11次