本帖最后由 zl78365336 于 2013-12-5 10:05 编辑
- while (!tsc.flag) {
- tsc.sellTicket(this); // 调用售票中心类
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-------------------------------------------
- if (ticketNum > 0) {
- int n = s.num+1;
- System.out.println("第--" + n+ "--售票窗口卖出了第" + ticketNum + "张票!");
- ticketNum--;
- } else {
- flag = true;
- }
这个程序结果正确,截取的两小段,flag = true; 感觉有点矛盾,求指点!
--------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------
- class TicketSealCenter {
- int ticketNum = 50;
- boolean flag = false; // 定义票是否卖完
-
- public TicketSealCenter(int num) {//定义一个改变票数的方法
- this.ticketNum = num;
- }
-
- public synchronized void sellTicket(SealWindow s) {
- if (ticketNum > 0) {
- int n = s.num+1;
- System.out.println("第--" + n+ "--售票窗口卖出了第" + ticketNum + "张票!");
- ticketNum--;
- } else {
- flag = true;
- }
- }
- }
- class SealWindow implements Runnable {
- int num;
- TicketSealCenter tsc;
- public SealWindow(int num, TicketSealCenter tsc) {
- this.num = num;
- this.tsc = tsc;
- }
-
- public final void run() {
- while (!tsc.flag) {
- tsc.sellTicket(this); // 调用售票中心类
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
|