多线程 模拟火车票售卖场景

编程入门 行业动态 更新时间:2024-10-07 23:17:58

<a href=https://www.elefans.com/category/jswz/34/1767532.html style=多线程 模拟火车票售卖场景"/>

多线程 模拟火车票售卖场景

一、模拟火车票售卖场景,三个窗口售卖A-B地的火车票,火车票共100张。

要求:
编号1-100 打印示例:窗口1售卖火车票66
窗口:写3个线程,


import java.util.Random;/*** @auther: 巨未* @DATE: 2019/4/12 0012 23:18* @Description:*/
class Tickets {private static int num = 0;public static synchronized int sale() {int i = ++num;return i> 100?-1:i;  //如果i>100返回-1.小于100返回i}
}
public class SaleTickets {public static void main(String[] args) {Thread thread1 = new Thread(new Runnable() {@Overridepublic void run() {Random random = new Random();int i = 0;while ((i = Tickets.sale()) != -1) {System.out.println(Thread.currentThread().getName() + "售卖票:" + i);try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}}}}, "窗口1");Thread thread2 = new Thread(new Runnable() {@Overridepublic void run() {Random random = new Random();int i = 0;while ((i = Tickets.sale()) != -1) {System.out.println(Thread.currentThread().getName() + "售卖票:" + i);try {Thread.sleep(random.nextInt(2000));} catch (InterruptedException e) {e.printStackTrace();}}}}, "窗口2");Thread thread3 = new Thread(new Runnable() {@Overridepublic void run() {Random random = new Random();int i = 0;while ((i = Tickets.sale()) != -1) {System.out.println(Thread.currentThread().getName() + "售卖票:" + i);try {Thread.sleep(random.nextInt(2000));} catch (InterruptedException e) {e.printStackTrace();}}}}, "窗口3");thread1.start();thread2.start();thread3.start();}
}

运行示例:

更多推荐

多线程 模拟火车票售卖场景

本文发布于:2024-02-28 01:23:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1767375.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多线程   火车票   场景

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!