Question
can you explain the unexplained lines in detail package pc; import java.util.concurrent.Semaphore; //have all the item class Q { int item; //initilizing sCon first with
can you explain the unexplained lines in detail
package pc; import java.util.concurrent.Semaphore; //have all the item class Q { int item; //initilizing sCon first with 0 premits , so that put() will be executed first static Semaphore sCon=new Semaphore(0); static Semaphore sProd=new Semaphore(1); //getting data from the buffer(storge) void get(){ try{ //before consumer start consuming data, it should take permit form sCon semaphore sCon.acquire();;} catch (InterruptedException e){ System.out.println("interruptedException caught");} //consumer will start consuming the item which is present in buffer System.out.println("consumer consumed item: "+item); //after consumed the item //ir releases sProd to notify producer sProd.release();} //put an item void put (int item){ try{ //before producer can produce an item , it must acquire a permit from semProd sProd.acquire();} catch (InterruptedException e){ System.out.println("interruptedException caught");} //producer produsing an item this.item=item; System.out.println("producer produced item: "+item); //after producer produce the item //it releases sCon to notify consumer after producer produce the item sCon.release();}}
class Producer implements Runnable{ //fill the item (Q) Q q; Producer(Q q ){ this.q=q; new Thread(this, "Producer").start(); } public void run(){ for(int i=0; i<5;i++) //producer put item q.put(i);} }
class Consumer implements Runnable{ //class will consume the (Q) data Q q; Consumer( Q q){ this.q=q; new Thread(this, "Consumer").start();} public void run(){ for(int i=0; i<5;i++) //consumer get items q.get();}} class Pc { public static void main(String[] args) { //creating buffer queue Q q=new Q(); //starting consumer thread new Consumer(q); //starting producer thread new Producer(q); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started