必须使用Threads强制执行此操作。客户数量作为命令行参数传入。
我在将custs Thread数组传递给start / run方法时遇到了一些麻烦。我不确定条件是否正确执行等待线程。如果我将customerThread类中的计数器更改为id,那么每次id为5的线程显示它时就会锁定它。
import java.io.*;
import java.util.Scanner;
import java.util.concurrent.locks.*;
public class CoffeeShop {
public static void main(String[] args)
{
Scanner infile = new Scanner(args[0]);
//Queue<Thread[]> CoffeeWaitingQueue = new LinkedList<Thread[]>();
//Queue<CustomerThread> CoffeeDrinkingQueue = new LinkedList<CustomerThread>();
if (args.length != 1) {
printUsage();
}
int num = 0;
try
{
num = Integer.parseInt(args[0]);
}
catch (NumberFormatException e)
{
printUsage();
}
System.out.println("Coffee Shop");
System.out .println("---------------------------------------------------"
+ "---------------------------------------------+--------"
+ "-------------------------------------------------------------------");
//Thread emp = new EmployeeThread();
//emp.start();
Thread[] custs = new Thread[num];
int counter = custs.length;
for (int i = 1; i < num; i++)
{
custs[i] = new CustomerThread(i);
custs[i].start();
}
for (int i = 1; i < num; i++)
{
try {
custs[i].join();
}
catch (InterruptedException e) {
}
}
System.exit(0);
}
private static void printUsage() {
System.out.println("Usage: java SandwichShop <num>");
System.out.println(" <num>: Number of customers.");
System.exit(-1);
}
public static void randomSleep(int max) {
try {
Thread.sleep((int) (Math.random() * max));
}
catch (InterruptedException e) {
}
}
}
class CustomerThread extends Thread {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
int counter = custs.length;
private int id;
public CustomerThread(int id)
{
this.id = id;
}
public void run()
{
drinkCoffee();
leaveShop();
}
private void drinkCoffee()
{
//int num = 0;
//int num = 1;
//num = customers;
//int counter = custs.length;
try{
lock.lock();
if(counter<5){
System.out.println("Customer is in seat " +counter);
++counter;
}else if(counter==5)
{
System.out.println("Customer is in seat " +counter);
System.out.println("Shop is now full");
while (counter>0) {
condition.await();
}
++counter;
System.out.println(" in "+""+counter);
}
}
catch (InterruptedException E1)
{
}
finally {
lock.unlock();
}
}
private void leaveShop()
{
try{
lock.lock();
System.out.println("Customer " + counter + " has left the seat");
--counter;
if(counter==0)
{
condition.signal();
}
}
finally {
lock.unlock();
}
}
}