zoukankan      html  css  js  c++  java
  • 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方法。

  • 相关阅读:
    Django之数据库--ORM
    Vue 父子组件
    axios封装
    DRF常用功能
    DRF框架之Serializer序列化器的反序列化操作
    Django、DRF有什么不同
    RESTFUL风格
    判断ViewPager滑动方向
    Incompatible integer to pointer conversion sending 'NSInteger' (aka 'int') to parameter of type 'id'
    AchartEngine使用
  • 原文地址:https://www.cnblogs.com/benxi/p/7347074.html
Copyright © 2011-2022 走看看