Skip to content
Advertisement

Java MultiThreading task, three smokers and one agent

the task consists of three smokers which are three threads and one class called Agent which has three attributes Tobacco, Lighters and Paper.
Smokers only have one of these items with them, agent class is supposed to put two items randomly on the table and then Smoker is supposed to check if they are missing those two items and pick them up so they can use them for smoking.

I am having an issue where my output is acting bit odd, smokers tend to pick all of the items they are missing at the same time even though i think i put that they are not allowed to do that.

Main class

JavaScript

I make one agent using a constructor and I pass it to the constructor of smokers.Each smoker has one item, ID, and agent.

Smoker class

JavaScript

In the smoker class function, I check if that agent has items needed for the current thread smoker and then I call the function that is in Agent class.

Agent class

JavaScript

A final class called Agent consists of a function that randomly puts two items on the table items are boolean and then I have function smoke that just checks which smoker was smoking and then sets everything to be false.

Output I am getting

JavaScript

This is wrong because in reality only one should be picking something at a time and then smoking it so others can have it also.

Thank you for your help sincerely.

Advertisement

Answer

This is wrong because in reality only one should be picking something at a time and then smoking it so others can have it also.

Because your Pusac Thread class run method is not guarded by anyone, you need to synchronize the run code block using the same monitor which you used to lock for smoke method. You can try synchronizing both smoke and run method by Agent.class

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement