Java多线程 编写三各类Ticket、SaleWindow、Tick…

2018-06-18 03:51:24来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折


package
com.swift; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TicketSaleCenter { public static void main(String[] args) { /* * 第6题: 编写三各类Ticket、SaleWindow、TicketSaleCenter分别代表票信息、售票窗口、售票中心。    * * 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。 */ Ticket tic = new Ticket(); tic.setTotal_num(1000); SaleWindow win = new SaleWindow(tic); Thread t1 = new Thread(win, "售票窗1"); Thread t2 = new Thread(win, "售票窗2"); Thread t3 = new Thread(win, "售票窗3"); t1.start(); t2.start(); t3.start(); } } class Ticket { private int total_num; private int sold_num; public int getTotal_num() { return total_num; } public void setTotal_num(int total_num) { this.total_num = total_num; } public int getSold_num() { return sold_num; } public void setSold_num(int sold_num) { this.sold_num = sold_num; } } class SaleWindow implements Runnable { private Ticket tic; public Ticket getTic() { return tic; } public void setTic(Ticket tic) { this.tic = tic; } public SaleWindow(Ticket tic) { super(); this.tic = tic; } @Override public void run() { while (true) { synchronized ("锁") { int totalNum = tic.getTotal_num(); int soldNum = tic.getSold_num(); if (totalNum > 0) { totalNum--; tic.setTotal_num(totalNum); soldNum++; tic.setSold_num(soldNum); System.out.println(Thread.currentThread().getName() + " 已卖出第 " + tic.getSold_num() + " 张票," + "剩余的票数是 " + tic.getTotal_num()); } } } } }

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:每日一模之工厂模式

下一篇:Spring Boot快速入门(二):http请求