잡자는 이발사 문제 Java 구현
import java.util.concurrent.Semaphore;
class Chair {
int[] cha;
int size;
int waitCustomer;
int in;
int out;
Semaphore cust;
Semaphore barb;
Chair(int size) {
cha = new int[size];
this.size = size;
waitCustomer = in = out = 0;
cust = new Semaphore(size);
barb = new Semaphore(0);
}
void down(int customer) {
if (waitCustomer == size) {
System.out.println("---Watting Chair is Full---");
}
try {
cust.acquire();
System.out.println("Customer" + customer + ": sit on the WatingChair...");
cha[in] = customer;
in = (in + 1) % size;
waitCustomer += 1;
barb.release();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
void up() {
if (waitCustomer == 0) {
System.out.println("Barber: sleeping");
}
try {
barb.acquire();
System.out.println("Customer" + cha[out] + ": move");
out = (out + 1) % size;
waitCustomer -= 1;
cust.release();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Customer extends Thread {
Chair cha;
int totalCustomer;
Customer(Chair cha, int totalCustomer) {
this.cha = cha;
this.totalCustomer = totalCustomer;
}
@Override
public void run() {
for (int i = 0; i < totalCustomer; i++) {
cha.down(i);
}
}
}
class Barber extends Thread { // 소비자
Chair cha;
int totalCustomer;
Barber(Chair cha, int totalCustomer) {
this.cha = cha;
this.totalCustomer = totalCustomer;
}
void getHairCut() {
System.out.println("Barber: HairCut-----");
}
@Override
public void run() {
for (int i = 0; i < totalCustomer; i++) {
cha.up();
getHairCut();
}
}
}
class SleepingBarber {
public static void main(String[] args) {
Chair chair = new Chair(3);
Customer customer = new Customer(chair, 7);
Barber barber = new Barber(chair, 7);
customer.start();
barber.start();
}
}