Professional Documents
Culture Documents
操作系统课程作业 6.11
操作系统课程作业 6.11
操作系统课程作业 6.11
11
学号:2019290009
姓名:何威
作业题⽬
The Sleeping-Barber Problem. A barbershop consists of a waiting room with n chairs and
a barber room with one barber chair. If there are no customers to be served, the barber
goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the
customer leaves the shop. If the barber is busy but chairs are available, then the customer
sits in one of the free chairs. If the barber is asleep, the customer wakes up the barber.
Write a program to coordinate the barber and the customers.
作业内容
Barber Class
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Random;
@Override
public void run(){
while(true){
try {
cavailable.acquire();
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 10000
+ 1000)); // Sleep to imitate length of time to cut hair
System.out.println("Customer Pays and leaves");
bavailable.release();
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.*;
class BarberShop{
public static void main(String[] args){
System.out.println("Opening up shop");
for(int i = 0; i < 1; i++) {
employees[i]= new Barber(spaces, barbers, customers);
openUp.execute(employees[i]);
}
while(true)
{
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(100,
1000 + 100)); // Sleep until next person gets in
}catch (InterruptedException e){}
Customer Class
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Random;
@Override
public void run(){
try {
cavailable.release();
if(bavailable.hasQueuedThreads()){
spaces.decrementAndGet();
System.out.println("Customer in waiting area");
bavailable.acquire();
spaces.incrementAndGet();
}
else{
bavailable.acquire();
}