写一个程序,模拟4个售票窗口共同卖100张火车票的程序。

写一个程序,模拟4个售票窗口共同卖100张火车票的程序。

1:使用继承Thread类方式实现()。
2:使用实现Runnable接口方式实现()。

第一种方式

   
   
package com.ljq.test; /** * 使用Thread类模拟4个售票窗口共同卖100张火车票的程序 * * 没有共享数据,每个线程各卖100张火车票 * * @author jiqinlin * */ public class ThreadTest { public static void main(String[] args){ new MyThread().start(); new MyThread().start(); new MyThread().start(); new MyThread().start(); } public static class MyThread extends Thread{ // 车票数量 private int tickets = 100 ; @Override public void run() { while (tickets > 0 ){ System.out.println( this .getName() + " 卖出第【 " + tickets --+ " 】张火车票 " ); } } } }

 

第二种方式

   
   
package com.ljq.test; /** * 使用Runnable接口模拟4个售票窗口共同卖100张火车票的程序 * * 共享数据,4个线程共同卖这100张火车票 * @author jiqinlin * */ public class RunnableTest { public static void main(String[] args) { Runnable runnable = new MyThread(); new Thread(runnable).start(); new Thread(runnable).start(); new Thread(runnable).start(); new Thread(runnable).start(); } public static class MyThread implements Runnable{ // 车票数量 private int tickets = 100 ; public void run() { while (tickets > 0 ){ System.out.println(Thread.currentThread().getName() + " 卖出第【 " + tickets --+ " 】张火车票 " ); } } } }

 

这两种线程创建方式的比较

使用Runnable接口
实际工作中,几乎所有的多线程应用都用实现Runnable这种方式。
Runnable适合多个相同程序代码的线程去处理同一资源的情况。把虚拟CPU(线程)同程序的代码、数据有效的分离,较好的体现了面向对象的设计思想。
避免由于Java的单继承特性带来的局限性。也就是如果新建的类要继承其他类的话,因为JAVA中不支持多继承,就只能实现java.lang.Runnable接口。
有利于程序的健壮性,代码能够被多个线程共享,代码与数据是独立的。

                      
继承Thread类
不能再继承他类了。
编写简单,可以直接操纵线程,无需使用Thread.currentThread()。
请查询API 获得currentThread方法的作用说明。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值