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

原文地址:https://www.cnblogs.com/dava/p/6675758.html