好得很程序员自学网

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

java实现Runnable接口适合资源的共享

本文为大家分享了java实现runnable接口适合资源的共享,供大家参考,具体内容如下

java当中,创建线程通常用两种方式:

1、继承thread类

2、实现runnable接口

但是在通常的开发当中,一般会选择实现runnable接口,原因有二:
1.避免单继承的局限,在java当中一个类可以实现多个接口,但只能继承一个类
2.适合资源的共享
原因1我们经常听到,但是2是什么呢?下面用一个例子来解释:
有5张票,分两个窗口卖:

继承thread类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

public class threaddemo {

   public static void main(string[] args) {

     hellothread t1 = new hellothread();

     t1.setname( "一号窗口" );

     t1.start();

     hellothread t2 = new hellothread();

     t2.setname( "二号窗口" );

     t2.start();

   }

 

}

class hellothread extends thread{

 

    private int ticket = 5 ;

   public void run() {

     while ( true ){

       system.out.println( this .getname()+(ticket--));

       if (ticket< 1 ) {

         break ; 

       }

     }

   }

 

}

运行结果:

很明显,这样达不到我们想要的结果,这样两个窗口在同时卖票,互不干涉。

实现thread类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public class threaddemo {

   public static void main(string[] args) {

     hellothread t = new hellothread();

     thread thread1 = new thread(t, "1号窗口" );

     thread1.start();

     thread thread2 = new thread(t, "2号窗口" );

     thread2.start();

   }

 

}

class hellothread implements runnable{

 

   private int ticket = 5 ;

   public void run() {

     while ( true ){

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

       if (ticket< 1 ) {

         break ; 

       }

     }

   }

 

}

运行结果:

这样两个窗口就共享了5张票,因为只产生了一个hellothread对象,一个对象里边有一个属性,这样两个线程同时在操作一个属性,运行同一个run方法。

这样就达到了资源的共享。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/xusheng_Mr/article/details/61938216

查看更多关于java实现Runnable接口适合资源的共享的详细内容...

  阅读:47次