如果一个类通过继承Thread来实现多线程的话,则不适合多个线程共享资源,而通过实现Runnable就可以做到这一点

如果一个类通过继承Thread来实现多线程的话,则不适合多个线程共享资源,而通过实现Runnable就可以做到这一点,下面给lz举个例子:
Java code
   
   
class MyTheard extends Thread{ private int num = 5 ; // 不能声明为静态的全局变量 public void run(){ for ( int i = 0 ;i < 100 ;i ++ ){ if (num > 0 ){ System.out.println(Thread.currentThread().getName() + " 卖票 " + " : " + (num -- )); } } } } public class TheardDemo01 { public static void main(String[] args) { MyTheard th1 = new MyTheard(); MyTheard th2 = new MyTheard(); MyTheard th3 = new MyTheard(); th1.start(); th2.start(); th3.start(); } }

输出结果:
Thread-0卖票:5
Thread-0卖票:4
Thread-0卖票:3
Thread-0卖票:2
Thread-0卖票:1
Thread-2卖票:5
Thread-2卖票:4
Thread-2卖票:3
Thread-2卖票:2
Thread-2卖票:1
Thread-1卖票:5
Thread-1卖票:4
Thread-1卖票:3
Thread-1卖票:2
Thread-1卖票:1
Java code
   
   
class MyThread implements Runnable { private int num = 5 ; public void run(){ for ( int i = 0 ;i < 100 ;i ++ ){ if (num > 0 ){ System.out.println(Thread.currentThread().getName() + " 卖票: " + " " + (num -- )); } } } }; public class ThreadDemo02 { public static void main(String[] args) { MyThread mt = new MyThread(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); } }

输出结果:
Thread-1卖票: 5
Thread-1卖票: 2
Thread-1卖票: 1
Thread-0卖票: 4
Thread-2卖票: 3
总结:
通过Rannable接口实现接口有如下的好处:
(1)适合于多个相同的程序代码的线程去处理同一资源。
(2)可以避免由于单继承带来的局限。
(3)增强了程序的健壮性,代码能够被多个线程共享,代码和数据独立。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值