Apologies for the delay in my reply, I code as a hobby in the evenings after my day job.
After much re-study I am now able to identify the faults in the original program and offer a solution that works.
The weather program was a way of modelling inter-thread cooperation:
Two threads sharing the same data (the simplest data structure – a class with field variables and getters/setters)Establsihing a happens – before relationship between two tasks. One thread’s execution to be contingent upon the second thread completing a required task.
In the weather program, the weather cannot be printed until the decider has decided what it is going to be.
This requires the two threads to share the same monitor (synonymous to ‘lock’).
The lock can be provided by any object, but a convenient object is an instance of
Java Object, since it is only its lock we’re interested in.
If like me, you are highly visual, I have attached a sort of flow diagram that shows two threads sharing the same lock in a happens – before relationship.
I explain it as follows:
The first thread acquires the lock and its task (the WeatherPrinter) checks whether a
Boolean flag has been set by the second thread running the WeatherDecider
If not:
It calls wait() allowing the second thread to acquire the monitor’s lock.The second thread’s task (WeatherDecider) can then decide the weather and set the flag to show it has been decided.
The task then issues a notify() on the monitor and releases the lock.The first thread re-aquires the lock (remember it’s the same lock)It sees that the weather flag is set and proceeds to print the weather.
If yes:
It reads the weather string and prints it.
Is the data in WeatherData, guarded from being changed by objects other than WeatherData? I believer so.
The object reference weatherData is declared final, meaning that it will always refer to a single unique WeatherData object.
Therefore, passing the weatherData reference always passes the same object.
Finally, thank you for taking an interest in the post. Maybe I should payback by responding to other people's posts. But I implore you gently - please make your code readable, it's half the battle !
Class WeatherData
Class WeatherPrinter
Class WeatherDecider
Main method class
Typical output: