• Thread和Runnable的子类调用


    实现线程的两种方式: 
    继承Thread类。 
    实现Runnable接口。


    下面是一个小案例:


     1 public class Thread和Runnable {
     2     public static void main(String[] args) {
     3         Runnable mr = new MyRunnable();
     4         Thread mt = new Mythread(mr);
     5         mt.start();
     6     }
     7 }
     8 class Mythread extends Thread{
     9     public Mythread(Runnable r){
    10         super(r);
    11     }
    12     @Override
    13     public void run() {
    14         // TODO Auto-generated method stub
    15         System.out.println("MyThread run");
    16         for(int i = 0;i < 100;i ++){
    17             System.out.println(Thread.currentThread().getName()+" = "+i);
    18         }
    19     }
    20 }
    21 class MyRunnable implements Runnable{
    22     @Override
    23     public void run() {
    24         // TODO Auto-generated method stub
    25         System.out.println("MyRunnable run");
    26         for(int i = 0;i < 100;i ++){
    27             System.out.println(Thread.currentThread().getName()+" = "+i);
    28         }
    29     }
    30 }

    最后执行的是MyThread里面的run方法。这是为什么呢? 
    当我们去查看源码,Runnable只有一个run方法,Thread实现Runnable接口,在Thread里面对于run方法的定义

    @Override
        public void run() {
            if (target != null) {
                target.run();
            }
        }

    也就是当Thread执行到run方法时,在Thread类定义了

     /* What will be run. */
        private Runnable target;

    会判断是否有target存在,如果有,则执行Runnable里面的run方法,但是有多态的存在,会直接执行子类MyThread的run方法,于是不会再去调用MyRunnable的run方法了,也就是不会去调用MyRunnable的run方法。

  • 相关阅读:
    HTML 5 视频/音频
    vue 未完待续
    asp.net中使用log4net
    图片预加载:jquery 图片预加载功能,可以实现先模糊在清晰的显示
    IIS配置PHP环境
    学习ASP.Net的过滤器
    最好用的jQuery插件,240多个,绝对的JQUERY插件库
    Windows7&IIS7.5部署Discuz全攻略
    AjaxPro使用
    ASP.NET XML读取、增加、修改和删除操作
  • 原文地址:https://www.cnblogs.com/benxi/p/7347074.html
Copyright © 2020-2023  润新知