Problem: Consider a system with three smoker processes and one agent process (mu
ID: 3567270 • Letter: P
Question
Problem: Consider a system with three smoker processes and one agent process (multiple threads problem). Each smoker continuously rolls a cigarette and then smokes it. But to roll and smoke a cigarette, the smoker needs three ingredients: tobacco, paper, and matches. One of the smoker processes has paper, another has tobacco, and the third has matches. The agent has an infinite supply of all three materials. Every time the agent places two of the ingredients on the table. The smoker who has the remaining ingredient then makes and smokes a cigarette, signaling the agent on completion. The agent then puts out another two of the three ingredients, and the cycle repeats. Write a program to synchronize the agent and the smokers using Java synchronization.
Requirements:
Explanation / Answer
/**
* This method will initialize all the 3 agents. Agents will perform following task:
*
* 1> Try to acquire agentSem Semaphore so that they release the ingredients
* 2> Places the ingredients on the table. This is done by releasing the respective ingredients semaphore thereby signaling the Pushers to takeover.
*/
public void initAgents() {
Thread agentA = new Thread() {
@Override
public void run() {
while(true) {
try {
agentSem.acquire();
System.out.println("Agent A is active and will release provide Tobacco & Paper ingredients.");
tobacco.release();
paper.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread agentB = new Thread() {
@Override
public void run() {
while(true) {
try {
agentSem.acquire();
System.out.println("Agent B is active and will release provide Match & Paper ingredients.");
match.release();
paper.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread agentC = new Thread() {
@Override
public void run() {
while(true) {
try {
agentSem.acquire();
System.out.println("Agent C is active and will release provide Tobacco & Match ingredients.");
tobacco.release();
match.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
agentA.start();
agentB.start();
agentC.start();
}
public static void main(String[] args) {
CigaretteSmoker cs = new CigaretteSmoker();
cs.initAgents();
cs.initPushers();
cs.initSmokers();
}
}
Thank You
Please Rate
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.