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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值