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;
}
}
關於線程同步問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
Web程序調式的利器 - Fiddler (HTTP協議監視工具)
hexzwj
2018-08-25 10:43:13
C# winform打開文件夾並選中指定文件
stoneson
2018-08-27 19:48:50
SOCKS 5協議詳解
stoneson
2018-08-27 19:48:49
#使用Socks5代理髮送UDP數據包
stoneson
2018-08-27 19:48:47
log4net 各種等級的消息 輸出到不同日誌文件的 配置文件方式
stoneson
2018-08-27 19:48:45
C#中如何獲取當前路徑的幾種方法
stoneson
2018-08-27 19:48:45
[轉]C#無邊框窗體移動的三種方法
stomach2008
2018-08-27 08:00:18
C#(Web)實現定時啓動任務
hexzwj
2018-08-25 10:43:16
設計模式初學者系列-觀察者模式
caoyoucheng
2018-08-25 08:49:21
C#做的一個加密/解密的類 - 清清月兒 .NET萬花筒 Asp.net技術 Asp.net教程 Asp.net源碼 Asp.net基礎 Asp.net控件 Asp.net入門 - CSDNBlog
caoyoucheng
2018-08-25 08:49:16
使用 C# 開發的 .NET 應用程序實例列表
caoyoucheng
2018-08-25 08:49:16
Webbrowser控件訪問iframe在線編輯器中的文本
chillystar
2018-08-26 02:19:36
Grid View Tree
hexzwj
2018-08-25 10:43:16