`
jjhpeopl
  • 浏览: 108708 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Thread和Runnable的区别

    博客分类:
  • java
阅读更多
Runnable比Thread要多一些优势,主要是以下两点
  • 避免点继承的局限,一个类可以继承多个接口。

<!--?xml version="1.0" encoding="UTF-8" standalone="no"?-->

  • 适合于资源的共享
第一点就不多说了,至于第二点看以下两个代码示例就清楚了
static class TicketThread extends Thread {

    // 一共十张票
    private int ticketNum 10;

    @Override
    public void run() {

        for (int i = 0; i < 20; i ++) {
            if (this.ticketNum 0) {
                System.out.println("卖票 ticket:" this.ticketNum --);
            }
        }
    }
}

public static void main(String[] args) {
    TicketThread thread1 = new TicketThread();
    TicketThread thread2 = new TicketThread();
    TicketThread thread3 = new TicketThread();
    thread1.start();
    thread2.start();
    thread3.start();
}
以上是使用Thread方式写的,其实程序最后总共卖出了30张票,每个线程卖了10张。再看一下示例:
static class TicketThread implements Runnable {
    // 一共十张票
    private int ticketNum 10;

    public void run() {

        for (int i = 0; i < 20; i ++) {
            if (this.ticketNum 0) {
                System.out.println("卖票 ticket:" this.ticketNum --);
            }
        }
    }
}

public static void main(String[] args) {
    TicketThread thread = new TicketThread();
    new Thread(thread).start();
    new Thread(thread).start();
    new Thread(thread).start();
}
使用Runnable方式的话,由于三个线程共享了资源,所以最终也是卖出10张票,不会多,从而实现了资源共享。
0
0
分享到:
评论
4 楼 qianban0201 2016-09-19  
例子举得很好
3 楼 jjhpeopl 2016-09-19  
kk_liang 写道
博主不觉得你举的栗子会造成线程不安全吗?另外类前面加上static关键字,请问你是写的静态嵌套类?


是静态嵌套类
的确例子会造成线程不安全,多谢提醒。
2 楼 kk_liang 2016-09-14  
博主不觉得你举的栗子会造成线程不安全吗?另外类前面加上static关键字,请问你是写的静态嵌套类?
1 楼 add2ws 2016-09-14  
例子举得很好

相关推荐

Global site tag (gtag.js) - Google Analytics