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方法。

  • 相关阅读:
    UI、JS框架----Bootstrap、Metro
    重构—改善既有代码的设计4——构筑测试体系
    重构—改善既有代码的设计3——代码的坏味道
    正则匹配-URL-域名
    pgAdmin的数据恢复
    重构—改善既有代码的设计2
    重构—改善既有代码的设计1
    Levenshtein Distance,判断字符串的相似性
    最大匹配字符串LCS,The Longest Common Substring
    email
  • 原文地址:https://www.cnblogs.com/benxi/p/7347074.html
Copyright © 2011-2022 走看看