线程实现火车票抢票程序

来源:互联网 发布:中国雷达技术 知乎 编辑:程序博客网 时间:2024/04/30 18:10

<span style="font-size:14px;">package H13;/** * 编写程序,实现火车票抢票程序,初始共50张车票,有三个线程进行处理, * 分别间隔10ms、20ms、50ms抢一张票,在车票数量为0时,就不再继续抢票, * 结束线程,最后统计所有线程分别抢到多少张票,并进行打印 * @author zhen * */class MThread implements Runnable {  //定义一个线程主体类private int ticket = 50;   //表示票数private int numA;          //统计ThreadA卖的票数private int numB;          //统计ThreadB卖的票数private int numC;   //统计ThreadC卖的票数@Overridepublic void run() {        //线程的主体方法for(int i = 0; i < 50; i++) {if(this.ticket == 0) {System.out.println("ThreadA 卖票:" + numA +   ",ThreadB 卖票:" + numB +   ",ThreadC 卖票:" + numC);break;}this.sale();}}public synchronized void sale() {   //定义同步方法if(this.ticket > 0) {   //表示有票if(Thread.currentThread().getName().equals("ThreadA")) {numA ++;try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.ticket--;  //卖票} else if(Thread.currentThread().getName().equals("ThreadB")) {numB ++;try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.ticket--;   //卖票} else {numC ++;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.ticket--;  //卖票}}}}public class Ticket {public static void main(String args[]) {MThread mt = new MThread();   //线程主体类Thread t1 = new Thread(mt,"ThreadA");Thread t2 = new Thread(mt,"ThreadB");Thread t3 = new Thread(mt,"ThreadC");t1.start();t2.start();t3.start();}}</span>


0 0