• 某类继承thread,同时实现runnable


    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是这样实现的

    1. @Override  
    2. public void run() {  
    3.     if (target != null) {  
    4.         target.run();  
    5.     }  
    6. }  

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

  • 相关阅读:
    【664】日常记录
    【663】dataframe 删掉指定行或者列
    【662】TensorFlow GPU 相关配置
    【661】Python split 指定多个分隔符
    【660】TensorFlow 或者 keras 版本问题
    FFMPEG视音频编解码
    cpplint中filter参数
    升级pip之后出现sys.stderr.write(f“ERROR: {exc}“)
    特征点三角化恢复3D点
    VIO——陀螺仪零偏估计
  • 原文地址:https://www.cnblogs.com/tiger-fu/p/8951940.html
Copyright © 2020-2023  润新知