好得很程序员自学网

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

详解多线程及Runable 和Thread的区别

thread和runnable区别

执行多线程操作可以选择
继承thread类
实现runnable接口

1.继承thread类

以卖票窗口举例,一共5张票,由3个窗口进行售卖(3个线程)。
代码:

?

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

package thread;

public class threadtest {

     public static void main(string[] args) {

         mythreadtest mt1 = new mythreadtest( "窗口1" );

         mythreadtest mt2 = new mythreadtest( "窗口2" );

         mythreadtest mt3 = new mythreadtest( "窗口3" );

         mt1.start();

         mt2.start();

         mt3.start();

     }

}

class mythreadtest extends thread{

     private int ticket = 5 ; 

     private string name;

     public mythreadtest(string name){

         this .name = name;

     }

   public void run(){ 

      while ( true ){

        if (ticket < 1 ){ 

         break ;

        } 

        system.out.println(name + " = " + ticket--); 

      } 

   }

}

执行结果:
窗口1 = 5
窗口1 = 4
窗口1 = 3
窗口1 = 2
窗口1 = 1
窗口2 = 5
窗口3 = 5
窗口2 = 4
窗口3 = 4
窗口3 = 3
窗口3 = 2
窗口3 = 1
窗口2 = 3
窗口2 = 2
窗口2 = 1
结果一共卖出了5*3=15张票,这违背了"5张票"的初衷。
造成此现象的原因就是:

?

1

2

3

4

5

6

mythreadtest mt1 = new mythreadtest( "窗口1" );

     mythreadtest mt2 = new mythreadtest( "窗口2" );

     mythreadtest mt3 = new mythreadtest( "窗口3" );

     mt1.start();

     mt2.start();

     mt3.start();

一共创建了3个mythreadtest对象,而这3个对象的资源不是共享的,即各自定义的ticket=5是不会共享的,因此3个线程都执行了5次循环操作。

2.实现runnable接口

同样的例子,代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package thread;

public class runnabletest {

     public static void main(string[] args) {

         myrunnabletest mt = new myrunnabletest();

         thread mt1 = new thread(mt, "窗口1" );

         thread mt2 = new thread(mt, "窗口2" );

         thread mt3 = new thread(mt, "窗口3" );

         mt1.start();

         mt2.start();

         mt3.start();

     }

}

class myrunnabletest implements runnable{

     private int ticket = 5 ; 

     public void run(){ 

      while ( true ){

          if (ticket < 1 ){ 

              break ;

          } 

          system.out.println(thread.currentthread().getname() + " = " + ticket--); 

      } 

   }

}

结果:

窗口1 = 5
窗口1 = 2
窗口3 = 4
窗口2 = 3
窗口1 = 1

结果卖出了预期的5张票。
原因在于:

?

1

2

3

4

5

6

7

myrunnabletest mt = new myrunnabletest();

thread mt1 = new thread(mt, "窗口1" );

thread mt2 = new thread(mt, "窗口2" );

thread mt3 = new thread(mt, "窗口3" );

mt1.start();

mt2.start();

mt3.start();

只创建了一个myrunnabletest对象,而3个thread线程都以同一个myrunnabletest来启动,所以他们的资源是共享的。

以上所述是小编给大家介绍的多线程及runable 和thread的区别详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://blog.csdn.net/qq_43499096/article/details/89048216

查看更多关于详解多线程及Runable 和Thread的区别的详细内容...

  阅读:19次