彻底理解Runnable和Thread的区别

  • Post author:
  • Post category:其他


昨天去面试,面试官问了一个问题:Runnable和Thread有什么区别,因为针对这个问题以前有背过,并且网上大多数都是这些结论,所以脱口而出:

1.Thread有单继承的问题;
2.Runnable便于实现资源共享,而Thread不能;

使用Thread实现多线程

public class MyThread extends Thread {

    private int ticket = 5;

    @Override
    public void run() {
        while (true) {
            System.out.println("Thread ticket = " + ticket--);
            if (ticket < 0) {
                break;
            }
        }
    }

}

public class Test {
    public static void main(String[] args) {

            //Test Thread

        new MyThread().start();
        new MyThread().start();

    }
}
    
执行结果如下:
Thread ticket = 5
Thread ticket = 4
Thread ticket = 3
Thread ticket = 2
Thread ticket = 1
Thread ticket = 0
Thread ticket = 5
Thread ticket = 4
Thread ticket = 3
Thread ticket = 2
Thread ticket = 1
Thread ticket = 0

并不能实现资源共享,跟以前背的面试题答案一样;但真的是这样吗?我们仔细看一下,代码中我们创建了两个MyThread对象,每个对象都有自己的ticket成员变量,当然会多卖1倍。现在我们重新测试一下,请看测试代码:

public class Test {
    public static void main(String[] args) {

            //Test Thread

        MyThread t1 = new MyThread();
        new Thread(t1).start();
        new Thread(t1).start();
    }
}

测试结果如下:
Thread ticket = 5
Thread ticket = 4
Thread ticket = 3
Thread ticket = 2
Thread ticket = 1
Thread ticket = 0
Thread ticket = -1

可以看到这次我们只创建了一个MyThread对象,并没出现卖两倍票的情况,Thread也可以实现资源共享。

因为多线程访问同一变量会有并发问题(需要加锁),所以Thread正确的写法如下:

public class MyThread extends Thread {

    private int ticket = 5;

    @Override
    public void run() {
        if (ticket > 0) {
            synchronized (this) {
                if (ticket > 0) {
                    while (true) {
                        System.out.println("Thread:" + Thread.currentThread().getName() + "--Thread ticket = " + ticket--);
                        if (ticket < 0) {
                            break;
                        }
                    }
                }
            }
        }
    }

}

public class Test {
    public static void main(String[] args) {

            //Test Thread

        MyThread t1 = new MyThread();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
    }
}

执行结果如下:
Thread:Thread-1--Thread ticket = 5
Thread:Thread-1--Thread ticket = 4
Thread:Thread-1--Thread ticket = 3
Thread:Thread-1--Thread ticket = 2
Thread:Thread-1--Thread ticket = 1
Thread:Thread-1--Thread ticket = 0

现在看Thread和Runnable的源码:


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

    private volatile String name;
    private int            priority;
    private Thread         threadQ;
    private long           eetop;
    
    

@FunctionalInterface
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()方法和start()方法的区别

线程的run()方法是由java虚拟机直接调用的,如果我们没有启动线程(没有调用线程的start()方法)而是在应用代码中直接调用run()方法,那么这个线程的run()方法其实运行在当前线程(即run()方法的调用方所在的线程)之中,而不是运行在其自身的线程中,从而违背了创建线程的初衷;

下面是一个用来说明start()方法和run()方法的区别的实例:

public class WelcomThread extends Thread {


//在该方法中实现线程的任务逻辑

public void run() {


//获取当前正在执行的线程名称

System.out.println(Thread.currentThread().getName());

}

}

public class TestDemo1 {


public static void main(String[] args) {


Thread welcome = new WelcomThread();  //创建线程(动态规划)

welcome.run();  //直接调用run()方法

System.out.println(Thread.currentThread().getName());

Thread welcome1 = new WelcomThread();  //创建线程

welcome1.start();  //启动线程

}

}

运行结果:

main

main

Thread-1

结论:1、其实Thread也就是实现了Runnable接口,提供了更多的方法而已。所以说Thread与Runnable并没有什么区别。

2、如果硬要说有什么区别的话,那就是类与接口的区别,继承与实现的区别。

3、没有调用start方法,则在当前调用线程运行,是违背了创建线程的初衷

4、正确的调用方法则是调用start方法

5、只调用run方法也是可以的,只是运行在当前线程而已,非新建线程