java关于线程同步的问题

来源:百度知道 编辑:UC知道 时间:2024/05/31 01:01:24
java关于线程同步的问题(高分悬赏)

题目说明一下,票是5元一张,买票的人持有的是5元或10的钞票。。。持有5元的能立即买到票,10元的需要有零钱找才能买到,否则等待。初始状态是售票员那没有零钱的。
没有零钱找时需要等待的顾客可以不需要考虑先来先买的规则。
以下是程序,不知道问题出在哪

/*我这明明只有14张票,却卖掉了15张,才提示售票结束
期望的答案的是卖到第15个人的时候告诉他,票已售完。再结束
错在哪呢?*/
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--

--memontoes;

仔细看看

少了个判断语句
SalesLady类ruleForSale()中try catch之后的
======================================
memontoes--;
five -= 1;
ten++;
s = "给你票," + "找你5元。";
======================================
这四句放到
if(memontoes>0){}中

--------------------------------------
另外while (five < 1) {...}
这里面逻辑有问题 在持10元的比持5元的人多的时候
可能会有一些线程会死循环困在里面
应该判断在memontoes=0时,break出来或return

楼上的判断有道理,你减时应该判断当前的数量,但是我觉得你跳出循环的条件判断有问题

if (memontoes == 0)

这里可以考虑一下把条件更改一下,他不一定是绝对等于0,你可以写成<1,然后加输出看看

int moneies[] = { 10, 10, 5, 10, 5, 10, 5, 5, 10, 5, 10, 5, 5, 10, 5};
楼主自己数一下,你这里可是定义了15个呀!!