Consider a system with three smoker processes and one agent process (multiple th
ID: 3566474 • Letter: C
Question
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
? One class for Smoker that you should create 3 threads, and one class for agent that you
have one thread.
? You should show that your solution works by having each smoker thread smoke three
cigarettes at least.
? Print out the result for some long period and analysis your result.
? Finally you need to analysis to see if deadlock occurs? If yes, under what condition?
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