共有100张票,通过3个窗口同时售票,使用两种方法,完成多线程售票
时间: 2023-05-20 09:05:37 浏览: 108
可以使用 synchronized 关键字或者 Lock 接口来实现多线程售票。下面是使用 synchronized 关键字的示例代码:
public class TicketSeller implements Runnable {
private int tickets = 100;
@Override
public void run() {
while (tickets > 0) {
synchronized (this) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "售出第" + tickets + "张票");
tickets--;
}
}
}
}
}
public class Main {
public static void main(String[] args) {
TicketSeller ticketSeller = new TicketSeller();
Thread thread1 = new Thread(ticketSeller, "窗口1");
Thread thread2 = new Thread(ticketSeller, "窗口2");
Thread thread3 = new Thread(ticketSeller, "窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
使用 Lock 接口的示例代码如下:
public class TicketSeller implements Runnable {
private int tickets = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (tickets > 0) {
lock.lock();
try {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "售出第" + tickets + "张票");
tickets--;
}
} finally {
lock.unlock();
}
}
}
}
public class Main {
public static void main(String[] args) {
TicketSeller ticketSeller = new TicketSeller();
Thread thread1 = new Thread(ticketSeller, "窗口1");
Thread thread2 = new Thread(ticketSeller, "窗口2");
Thread thread3 = new Thread(ticketSeller, "窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
阅读全文