某类继承thread,同时实现runnable

时间:2021-10-18 17:32:16
[java] view plain copy
  1. package com.giserve.test;  
  2.   
  3. public class ThreadTest {  
  4.     public static void main(String[] args) {  
  5.         new Thread(new Runnable() {  
  6.               
  7.             @Override  
  8.             public void run() {  
  9.                 while(true){  
  10.                     try {  
  11.                         Thread.sleep(1000);  
  12.                         System.out.println("Thread1::"+Thread.currentThread().getName());  
  13.                     } catch (InterruptedException e) {  
  14.                         // TODO Auto-generated catch block  
  15.                         e.printStackTrace();  
  16.                     }  
  17.                 }  
  18.             }  
  19.         }){  
  20.             @Override  
  21.             public void run() {  
  22.                 while(true){  
  23.                     try {  
  24.                         Thread.sleep(1000);  
  25.                         System.out.println("Thread0::"+Thread.currentThread().getName());  
  26.                     } catch (InterruptedException e) {  
  27.                         // TODO Auto-generated catch block  
  28.                         e.printStackTrace();  
  29.                     }  
  30.                 }  
  31.             };  
  32.         }.start();  
  33.     }  
  34. }  

结果是:

Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0

在JDK源码中Thread线程中的run是这样实现的

[java] view plain copy
  1. @Override  
  2. public void run() {  
  3.     if (target != null) {  
  4.         target.run();  
  5.     }  
  6. }  

结论:
target代表的是构造Thread时传入的Runable对象,疑问为什么会是Thread-0,原因是当子类覆盖父类后,上面的run方法的target就不存在了。所以执行的run方法就是Thread子类的。