關於線程同步問題

 class SalesLady {
   
int memontoes, five, ten;

   
public synchronized String ruleForSale(int num, int money) {
        String s
= null;
       
if (memontoes == 0)
           
return "對不起,已經售完";
       
if (money == 5) {
            memontoes
--;
            five
++;
            s
= "給你票," + "你的錢正好。";
        }
else if (money == 10) {
           
while (five < 1) {
               
try {
                    System.out.println(
"" + num + "號顧客用10元購票,請等待");
                    wait();
                }
catch (InterruptedException e) {
                }
            }
            memontoes
--;
            five
-= 1;
            ten
++;
            s
= "給你票," + "找你5元。";
        }
        notifyAll();
       
return s;
    }

    SalesLady(
int m, int f, int t) {
        memontoes
= m;
        five
= f;
        ten
= t;
    }
}

public class 八_5 extends java.applet.Applet {
   
static SalesLady saleslady = new SalesLady(14, 0, 0);
   
public void start() {
       
int moneies[] = { 10, 10, 5, 10, 5, 10, 5, 5, 10, 5, 10, 5, 5, 10, 5};
        Thread[] aThreadArray
= new Thread[20];
        System.out.println(
"現在開始售票:");
       
for (int i = 0; i < moneies.length; i++) {
            aThreadArray[i]
= new Thread(new CustomerClass(i + 1, moneies[i])); aThreadArray[i].start(); } WhileLoop: while (true) {
           
for (int i = 0; i < moneies.length; i++)
               
if (aThreadArray[i].isAlive())
                   
continue WhileLoop;
           
break;
        }
        System.out.println(
"票已售完");
    }
}

class CustomerClass implements Runnable {
   
int num, money;

   
public void run() {
       
try {
            Thread.sleep(
10);
        }
       
catch (InterruptedException e) {
        }
        System.out.println(
"我是" + num + "號顧客,用" + money + "元購票,售票員說:"
               
+ 八_5.saleslady.ruleForSale(num, money));
    }

    CustomerClass(
int n, int m) {
        num
= n;
        money
= m;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章