如下内容内容是关于java 模拟售票,多线程的同步与互斥的内容。 public class SaleTicket {
public static void main(String[] args) {
Ticket t = new Ticket(50);
set.start();
for (int i = 1; i <= 52; i++) {
getTicket get = new getTicket(t, "买票者 " + i + " ");
get.start();
}
}
} class Ticket {
public Ticket(int ticketNum) {
this.ticketNum = ticketNum;
}
public synchronized void getTicket(String name) throws InterruptedException {
while (!write && read) {
+ " 买票等待。。。");
this.wait();
}
if (ticketNum > 0) {
+ " 买票成功,号码=" + ticketNum);
this.notifyAll();
read = false;
+ " 没有买到票");
}
}
public synchronized void sellTicket(String name)
throws InterruptedException {
while (ticketNum > 0) {
while (write) {
System.out.println(name + " 处理业务,售票等待。。。");
this.wait();
}
if (ticketNum > 0) {
System.out.println(name + " 开始售票,号码=" + ticketNum);
}
write = true;
this.notifyAll();
}
System.out.println(name + " 对不起,售票已经售完!");
}
public void subTicketNum() {
if (this.ticketNum > 0)
this.ticketNum = this.ticketNum - 1;
}
public int getTicketNum() {
return ticketNum;
}
}
class getTicket extends Thread {
public getTicket(Ticket d, String name) {
this.d = d;
this.name = name;
}
public void run() {
try {
d.getTicket(name);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class setTicket extends Thread { Ticket d;
public setTicket(Ticket d) {
this.d = d;
}
public void run() {
try {
d.sellTicket("售票员 1 ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}