zoukankan      html  css  js  c++  java
  • Thread 与 Runnable 混合使用测试

    package com.dava;
    
    public class TesThread extends Thread implements Runnable {
        public void run() {
            System.out.println("运行成功!");
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Thread t=new Thread(new TesThread());
            t.start();
    
        }
    
    }

    运行结果:

    运行成功!

    程序继承了Thread 实现Runnable,接口的方法是需要全部实现的,而Runnable接口源码如下:

    public
    interface Runnable {
        /**
         * When an object implementing interface <code>Runnable</code> is used 
         * to create a thread, starting the thread causes the object's 
         * <code>run</code> method to be called in that separately executing 
         * thread. 
         * <p>
         * The general contract of the method <code>run</code> is that it may 
         * take any action whatsoever.
         *
         * @see     java.lang.Thread#run() 
         */
        public abstract void run();
    }
    

     所以有run();方法程序会正常执行.

    单独继承Runnable方法:

    public class ImpInterface implements Runnable {
        
        public void run() {
            // TODO Auto-generated method stub
    
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.out.println("123465");
        }
    
    }

    如果部实现run方法会出现异常。但是在上面的ji集成了Thread又实现了Runnable,可以部实现Run方法,程序会正常运行。

    package com.dava;
    
    public class TesThread extends Thread implements Runnable {
    //    public void run() {
    //        System.out.println("运行成功!");
    //    }
        public void print() {
            System.out.println("1231456");
    
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            
    //        Thread t=new Thread(new TesThread());
    //        t.start();
            new TesThread().print();
            
    
        }
    
    }

    运行结果:1231456

    为什么不实现接口也行呢?看下图

    Thread也实现了Runnable接口,实现了Run方法,子类默认继承了父类的方法,所以也实现了Runnable的run方法。

  • 相关阅读:
    在MPTCP中引入流量监控——bwm-ng的使用说明
    Ubuntu下配置MPTCP
    实现两台MPTCP主机之间的通信——VSFTPD的配置与使用
    Google 辟谣,Android 和 Chrome OS 不合并
    paper-7
    计算机网络方面国际三大顶尖会议
    谷歌物联网操作系统Android Things揭开面纱
    张纯如
    Android binder机制之 5 --(创建binder服务)
    【BZOJ 1491】[NOI2007]社交网络
  • 原文地址:https://www.cnblogs.com/dava/p/6675758.html
Copyright © 2011-2022 走看看