生成理发店问题的Java代码
时间: 2023-05-24 17:04:53 浏览: 57
以下是一个简单的Java代码,用于模拟理发店的服务流程:
```
import java.util.LinkedList;
import java.util.Queue;
public class BarberShop {
private Queue<Customer> waitingCustomers;
public BarberShop() {
waitingCustomers = new LinkedList<Customer>();
}
public synchronized void addCustomer(Customer customer) {
waitingCustomers.offer(customer);
notifyAll();
}
public synchronized Customer getNextCustomer() {
while (waitingCustomers.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return waitingCustomers.poll();
}
}
public class Barber extends Thread {
private BarberShop shop;
private String name;
public Barber(BarberShop shop, String name) {
this.shop = shop;
this.name = name;
}
public void run() {
while (true) {
Customer customer = shop.getNextCustomer();
System.out.println("Barber " + name + " is cutting hair of customer " + customer.getName());
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class Customer extends Thread {
private BarberShop shop;
private String name;
public Customer(BarberShop shop, String name) {
this.shop = shop;
this.name = name;
}
public void run() {
System.out.println("Customer " + name + " enters the shop");
shop.addCustomer(this);
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Customer " + name + " has left the shop");
}
public String getName() {
return name;
}
public synchronized void done() {
notifyAll();
}
}
public class Main {
public static void main(String[] args) {
BarberShop shop = new BarberShop();
Barber barber1 = new Barber(shop, "Bob");
Barber barber2 = new Barber(shop, "Joe");
barber1.start();
barber2.start();
Customer customer1 = new Customer(shop, "Alice");
Customer customer2 = new Customer(shop, "Dave");
Customer customer3 = new Customer(shop, "Karen");
customer1.start();
customer2.start();
customer3.start();
}
}
```
主类Main创建了一个理发店对象和两个理发师线程对象,以及三个顾客线程对象。当顾客进入理发店时,它们将被添加到等待队列中,理发师从等待队列中获取下一个顾客并执行理发过程。当理发完成时,顾客将通知挂起的线程继续执行。