zoukankan      html  css  js  c++  java
  • 线程

    关于选择继承Thread还是实现Runnable接口?

    其实Thread也是实现Runnable接口的

    1
    2
    3
    4
    5
    6
    7
    8
    class Thread implements Runnable {
        //…
    public void run() {
            if (target != null) {
                 target.run();
            }
            }
    }

    其实Thread中的run方法调用的是Runnable接口的run方法。不知道大家发现没有,Thread和Runnable都实现了run方法,这种操作模式其实就是代理模式。关于代理模式,我曾经写过一个小例子呵呵,大家有兴趣的话可以看一下:http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html

    Thread和Runnable的区别:

    如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    /**
     * @author Rollen-Holt 继承Thread类,不能资源共享
     * */
    class hello extends Thread {
        public void run() {
            for (int i = 0; i < 7; i++) {
                if (count > 0) {
                    System.out.println("count= " + count--);
                }
            }
        }
      
        public static void main(String[] args) {
            hello h1 = new hello();
            hello h2 = new hello();
            hello h3 = new hello();
            h1.start();
            h2.start();
            h3.start();
        }
      
        private int count = 5;
    }

    【运行结果】:

    count= 5

    count= 4

    count= 3

    count= 2

    count= 1

    count= 5

    count= 4

    count= 3

    count= 2

    count= 1

    count= 5

    count= 4

    count= 3

    count= 2

    count= 1

    大家可以想象,如果这个是一个买票系统的话,如果count表示的是车票的数量的话,说明并没有实现资源的共享。

    我们换为Runnable接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class MyThread implements Runnable{
      
        private int ticket = 5//5张票
      
        public void run() {
            for (int i=0; i<=20; i++) {
                if (this.ticket > 0) {
                    System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
                }
            }
        }
    }
    public class lzwCode {
          
        public static void main(String [] args) {
            MyThread my = new MyThread();
            new Thread(my, "1号窗口").start();
            new Thread(my, "2号窗口").start();
            new Thread(my, "3号窗口").start();
        }
    }

      

     

    【运行结果】:

    count= 5

    count= 4

    count= 3

    count= 2

    count= 1

     

    总结一下吧:

    实现Runnable接口比继承Thread类所具有的优势:

    1):适合多个相同的程序代码的线程去处理同一个资源

    2):可以避免java中的单继承的限制

    3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立。

  • 相关阅读:
    设计模式
    jQuery回到顶部插件jQuery GoUp
    CentOS7+Tomcat 生产系统部署
    iOS 时间戳转换为时间
    iOS开发系列--Swift 3.0
    IOS
    iOS之宏定义#define
    #define和预编译指令
    iOS宏定义的使用与规范
    ios十进制、十六进制字符串,byte,data等之间的转换
  • 原文地址:https://www.cnblogs.com/lyz459/p/4313671.html
Copyright © 2011-2022 走看看