本帖最后由 狼色幽默 于 2016-10-15 16:40 编辑
问题我已经想出来了,弄三个线程卖票,每次执行一个,睡眠另外2个,运行完后随机唤醒再运行,每次运行都是随机卖1~3张票,代码比较复杂,但是基本能实现,这里是部分代码
[Java] 纯文本查看 复制代码
class window {
private static int flag = 1;
private static int tickets = 100;
public void win1() throws InterruptedException {
while(true) {
synchronized (this) {
if(flag != 1) this.wait();
if(tickets > 0){
Random r = new Random();
int count = r.nextInt(3)+1;
for (int i = 0; i < count; i++) {
Thread.sleep(50);
System.out.println("窗口1卖出了1张票,还剩" + tickets-- + "张票");
}
}else {
System.out.println("票卖完了");
break;
}
flag = 2;
this.notify();
}
}
}
public void win2() throws InterruptedException {
while(true) {
synchronized (this) {
if(flag != 2) this.wait();
if(tickets > 0){
Random r = new Random();
int count = r.nextInt(3)+1;
for (int i = 0; i < count; i++) {
Thread.sleep(50);
System.out.println("窗口2卖出了1张票,还剩" + tickets-- + "张票");
}
}else {
System.out.println("票卖完了");
break;
}
flag = 3;
this.notify();
}
}
}
public void win3() throws InterruptedException {
while(true) {
synchronized (this) {
if(flag != 3) this.wait();
if(tickets > 0){
Random r = new Random();
int count = r.nextInt(3)+1;
for (int i = 0; i < count; i++) {
Thread.sleep(50);
System.out.println("窗口3卖出了1张票,还剩" + tickets-- + "张票");
}
}else {
System.out.println("票卖完了");
break;
}
flag = 1;
this.notify();
}
}
}
} |