//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        CSE 428 - SPRING 2001                         //
//                                                                      //
//                       Solution of Assignment #4                      //
//                                                                      //
//                         File Scheduler.java                          //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

// Definition of the scheduler

class Scheduler 
{
    private int numberOfTasks;
    private int next; // Next task that can start
    private boolean[] A; // semaphores

    public Scheduler(int numberOfTasks)
    {
        this.numberOfTasks = numberOfTasks;
        next = 0;
        A = new boolean[numberOfTasks];
        for (int n=0; n<numberOfTasks; n++) { 
           A[n] = false; 
        }
    }

    public synchronized void requestPermissionToStart(String name, int n) 
        throws InterruptedException
    {
        while (A[n] || next!=n) wait();
        A[n] = true;
        next++;
        if (next==numberOfTasks) next = 0;
        notifyAll();      
        System.out.println(name+" starts task "+n);  
    }

    public synchronized void notifyEndOfTask(String name, int n)
    {
        A[n] = false;
        notifyAll(); 
        System.out.println("                    "+name+" ends task "+n);
    }
}     

//////////////////////////////////////////////////////////////////////////
