java 22

多线程的代码实现:

方式2:实现Runnable接口
  步骤:
    A:自定义类MyRunnable实现Runnable接口
    B:重写run()方法
    C:创建MyRunnable类的对象
    D:创建Thread类的对象,并把C步骤的对象作为构造参数传递(2种方法)
        a:Thread(Runnable target)
        b:Thread(Runnable target, String name)

方式2的好处:

  A:因为java的继承方式是单继承,方式2可以避免java单继承带来的局限性

  B:适合多个相同的程序代码去处理同一个资源的情况,把线程同程序的代码,数据有效分离,较好的体现了面向对象的设计思想

首先看下方式2的代码实现,再解释 好处B

先执行步骤A、B,创建个自定义类

1 public class MyRunnable implements Runnable {
2 
3     public void run() {
4         for(int x = 1; x < 100; x++){
5             System.out.println(Thread.currentThread().getName()+"--"+x);
6         }
7 
8     }
9 }

接着执行步骤C、D,创建个测试类

 1 public class MyRunnableDemo {
 2 
 3     public static void main(String[] args) {
 4         // 创建MyRunnable类的对象
 5         MyRunnable mr = new MyRunnable();
 6         
 7         //创建Thread类的对象,并把C步骤的对象作为构造参数传递
 8         /*
 9         //方式1:Thread(Runnable target)
10         Thread t1 = new Thread(mr);
11         Thread t2 = new Thread(mr);
12         //给线程起名
13         t1.setName("哈士奇");
14         t2.setName("萨摩耶");
15 
16          */
17         //方式2 :Thread(Runnable target, String name)
18         Thread t1 = new Thread(mr,"哈士奇");
19         Thread t2 = new Thread(mr,"萨摩耶");
20         
21         //执行线程
22         t1.start();
23         t2.start();
24     }
25 
26 }

通过代码,可以发现。在测试类中,只创建了一次MyRunnable类的对象,而在方式1中,则需要执行几次线程,就要创建几次对象。(相同的程序代码的线程情况下)

所以说,方式2的好处B就体现在这里。

何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5933425.html