java中Thread类和Runnable接口区别

原创
2017/12/14 15:49
阅读数 166
AI总结

源码分析

这里只截取部分源码

Thread类

1 实现Runnable接口

public class Thread implements Runnable {}

2 有start()方法来启动线程

public synchronized void start() {
    threadStatus != 0)
        throw new IllegalThreadStateException();

3 有这样的构造方法:

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

此方法可以接受Runnable的对象,换句话说就是Thread类可以启动Runnable实现的多线程.

Runnable接口

只有run方法,此方法不是线程的启动方法

public interface Runnable {
    public abstract void run();
}

 

优缺点对比

实际开发中实现多线程肯定永远以实现Runnable接口为主

实现Runnable接口比继承Thread类有如下有点:

1 避免继承的局限,一个接口可以多实现

2 可以实现资源共享

 

实例

以卖票为例,总共10张票,3个窗口卖

public class MyThread extends Thread {

    private int tickets = 10;
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "--卖出票: " + tickets--);
            }
        }
    }

    public static void main(String[] args) {

        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();
        MyThread myThread3 = new MyThread();

        myThread1.start();
        myThread2.start();
        myThread3.start();

    }
}

 

运行结果如下:

Thread-1--卖出票: 1
Thread-0--卖出票: 1
Thread-2--卖出票: 1
Thread-0--卖出票: 2
Thread-0--卖出票: 3
Thread-0--卖出票: 4
Thread-0--卖出票: 5
Thread-0--卖出票: 6
Thread-0--卖出票: 7
Thread-0--卖出票: 8
Thread-0--卖出票: 9
Thread-0--卖出票: 10
Thread-1--卖出票: 2
Thread-1--卖出票: 3
Thread-1--卖出票: 4
Thread-1--卖出票: 5
Thread-1--卖出票: 6
Thread-1--卖出票: 7
Thread-1--卖出票: 8
Thread-1--卖出票: 9
Thread-1--卖出票: 10
Thread-2--卖出票: 2
Thread-2--卖出票: 3
Thread-2--卖出票: 4
Thread-2--卖出票: 5
Thread-2--卖出票: 6
Thread-2--卖出票: 7
Thread-2--卖出票: 8
Thread-2--卖出票: 9
Thread-2--卖出票: 10

每个线程都独立,不共享资源,如果真卖票就有问题了.

 

public class MyRunnable implements Runnable{
    private int tickets = 10;
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "--卖出票: " + tickets--);
            }
        }
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread1 = new Thread(myRunnable, "窗口1");
        Thread thread2 = new Thread(myRunnable, "窗口2");
        Thread thread3 = new Thread(myRunnable, "窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

 

运行结果如下:

窗口1--卖出票: 10
窗口2--卖出票: 9
窗口2--卖出票: 8
窗口3--卖出票: 8
窗口1--卖出票: 7
窗口3--卖出票: 5
窗口2--卖出票: 6
窗口3--卖出票: 3
窗口3--卖出票: 1
窗口1--卖出票: 4
窗口2--卖出票: 2

可以看出每个线程共享了对象myRunnable的资源,卖出票的总数是对的.

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
0
分享
AI总结
返回顶部
顶部