[Java] 纯文本查看 复制代码
class Ticket extends Thread {
private static int tickets = 100;
static Object obj = new Object();
public Ticket() {
super();
}
public Ticket(String s) {
super(s);
}
@Override
public void run() {
int count = 0;
while(true) {
synchronized (obj) {
if(tickets < 0) break;
if(count >= 3) break;
try{
Thread.sleep(100);
count++;
}catch(Exception e) {
e.printStackTrace();
}
System.out.println(getName() + ":还剩" + tickets-- + "张票");
}
}
}
}[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();
}
}
}
}