多线程 模拟火车票售卖场景"/>
多线程 模拟火车票售卖场景
一、模拟火车票售卖场景,三个窗口售卖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();}
}
运行示例:
更多推荐
多线程 模拟火车票售卖场景
发布评论