Thread和Runable 的区别

一、从底层源码:

1、Thread是一个实现Runable接口的的类,Runable是一个接口。

class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();

    }

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();

}

可以看出Thread实现接口中的run方法,并构造了自己的方法,Runable 接口只有一个方法,即run();

2、其中两个钟都有run()方法和Start()方法

run()方法启动两个线程时,一个线程结束之后,才执行另一个线程,没有交互执行;start方法,可以交互执行,其实启动start方法,其实在jvm中会找run()方法。

3、启动来说

Thread 启动new Thread().start();Runable 中启动得靠Thread类中的方法

  public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);

    }

进行启动。

二、代码实现分析:

public class TestRunableAndThread {

    public static void main(String[] args){
    myTest m1 = new myTest();
    new Thread(m1).start();//Runable启动两个线程消耗100次
    new Thread(m1).start();//
    new myTe().start();//Thread 是创建两个线程对象,每个对象消耗100次
    new myTe().start();
    }
}
class myTe extends Thread{
int t=100;
public void run() {
while(true){
if(t>0){
       System.out.println(Thread.currentThread().getName() +   
          " is saling ticket " +t--);
}
else{
break;
}
}
}

class myTest implements Runnable{
int t=100;
@Override
public void run() {
while(true){
if(t>0){
       System.out.println(Thread.currentThread().getName() +   
          " is saling ticket runrunrurn " +t--);
}
else{
break;
}
}
}

创建线程的启动,以及启动线程的个数,消耗的次数都有很大的区别。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值