Java教程

java多线程模拟售票

本文主要是介绍java多线程模拟售票,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

售票类:

package duoxiancheng;

import java.util.concurrent.TimeUnit;

/**
 * @author yeqv
 * @program A2
 * @Classname Ticket
 * @Date 2022/1/28 23:04
 * @Email w16638771062@163.com
 */
public class Ticket implements Runnable {
    //未设置票数,默认为100
    private int num = 100;

    public Ticket() {
    }
//获取传入票数
    public Ticket(int num) {
        this.num = num;
    }


    public void run() {
        while (true) {
            //加锁,当一个进程进入时其他进程阻塞,防止数据出错
            synchronized (this) {
                try {
                    //延时1秒
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (num > 0) {
                    System.out.printf("[%s] 售出一张票,剩余%d张票%n", Thread.currentThread().getName(), --num);
                } else {
                    System.out.printf("%n[%s] 票已售完,停止售票。", Thread.currentThread().getName());
                    break;
                }
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

测试类:

package duoxiancheng;


/**
 * @author yeqv
 * @program A2
 * @Classname Test4
 * @Date 2022/1/28 23:03
 * @Email w16638771062@163.com
 */
public class Test4 {
    public static void main(String[] args) {
        //传入票数
        Ticket ticket = new Ticket(20);
        //创建四个新线程并且更名
        Thread thread = new Thread(ticket, "郑州站");
        Thread thread1 = new Thread(ticket, "郑州东站");
        Thread thread2 = new Thread(ticket, "郑州南站");
        Thread thread3 = new Thread(ticket, "郑州北站");
        //启动四个线程
        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();


    }
}

这篇关于java多线程模拟售票的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!