Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A group of N faculty members are sitting around a bowl of candy, which holds M p

ID: 3818160 • Letter: A

Question

A group of N faculty members are sitting around a bowl of candy, which holds M pieces of candy. Each of the N faculty members spends his life thinking and eating candy. They must have a piece of candy to think. One Teaching Assistant spends his life sleeping except that when the bowl is empty he is woken up and fills the candy bowl. Only one faculty member can access the bowl at a time.

1) Write a Java solution to the above program using a semaphore implementation for synchronization and mutual exclusion. Each faculty member should be a thread. The Teaching Assistant should be a thread.

2) Write a Java solution using a synchronized class representing the bowl.

Explanation / Answer

//Find code here

//Find Candy class here

package com.thread;

import java.util.concurrent.Semaphore;

public class Candy {

   synchronized public void candyEating(Semaphore semaphore){
       try {
           System.out.println("Candy available now "+semaphore.availablePermits());
           semaphore.acquire();
       } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       System.out.println(Thread.currentThread().getName()+" Eating candy and thinking..");
   }
}


//Find here Faculty class

package com.thread;

import java.util.concurrent.Semaphore;

public class Faculty implements Runnable{
   Semaphore semaphore = new Semaphore(4);
   Candy candy;
  
   Faculty(Candy candy){
       this.candy=candy;
   }

   public void run(){
      
       candy.candyEating(semaphore);
   }
}

//Find here TestFaculty class

package com.thread;

public class TestFaculty {

  
  
   public static void main(String[] args) {
      

       Candy candy=new Candy();
       Faculty faculty1 = new Faculty(candy);
       Thread t1 = new Thread(faculty1,"faculty1");
      
       Faculty faculty2 = new Faculty(candy);
       Thread t2 = new Thread(faculty1,"faculty2");
      
       Faculty faculty3 = new Faculty(candy);
       Thread t3 = new Thread(faculty1,"faculty3");
      
       Faculty faculty4 = new Faculty(candy);
       Thread t4 = new Thread(faculty1,"faculty4");
      
       t1.start();
       t2.start();
       t3.start();
       t4.start();
      
      
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote