2个窗口交替出售一张票,控制台可能会因为异步打印的原因出现连续打印一个窗口的票,但是票的奇偶肯定固定在一个窗口出售
public class WaitAndNodtify {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Seller1(ticket).start();
new Seller2(ticket).start();
}
static class Ticket{
public Integer count = 1000;
public Boolean isSeller1 = true;
}
static class Seller2 extends Thread{
private Ticket ticket;
Seller2(Ticket ticket){
this.ticket = ticket;
}
@Override
public void run() {
while(ticket.count > 0) {
synchronized(ticket) {
if(ticket.isSeller1) {
try {
ticket.wait();
} catch (InterruptedException e) {
}
}
if(ticket.count <= 0) {
continue;
}
System.err.println("窗口2售第【 "+ticket.count+" 】张票");
ticket.count--;
ticket.isSeller1=true;
ticket.notify();
}
}
}
}
static class Seller1 extends Thread{
private Ticket ticket;
Seller1(Ticket ticket){
this.ticket = ticket;
}
@Override
public void run() {
while(ticket.count > 0) {
synchronized(ticket) {
if(!ticket.isSeller1) {
try {
ticket.wait();
} catch (InterruptedException e) {
}
}
if(ticket.count <= 0) {
continue;
}
System.out.println("窗口1售第【 "+ticket.count+" 】张票");
ticket.count--;
ticket.isSeller1=false;
ticket.notify();
}
}
}
}
}
网友评论