I am currently studying the multithreaded programming and I am having a hard time mastering shared resources between threads.
I have two shared resources, time and alarm
I have three threads, one keeps updating time every second, one monitors time against alarm and finally one changes time and alarm at user request.
this is to be done using mutual exclusion semaphore, I have a simple setup described below:
Mainthread, program begins here, hoststimeandalarmcommon variables and instantiates sub threads.Ticksub-thread, sleeps every 1000ms, then modifiesMotherthread’stimevariableUserInputsub-thread, is blocked until a user input is caught, and modifies eithertimeoralarminMainthread.Alarmsub-thread, sleeps every 1000ms, goes off whenalarm==time
The Main thread keeps a mutex for each resource so only one thread can access it at a time.
Is such design reasonable or am I just over complicating things?
My first comment would be on the language you use, which may be an indication of some misunderstanding on your part. A thread doesn’t own any variables; this may mean that you have declared several custom subclasses of
Thread. If that is so, this would not be an advisable approach. Note thatThreadis just the name of a class, it is not the actual thread—exactly the same way asFileis not a file. You haven’t posted any code so I must resort to guesswork, but if what I describe is true then you should redesign. Use plain classes (that don’t subclass anything) and instantiateThreadwith aRunnable.Second, it is not very clear what you imply by “mutex” as this is not a term defined by the Java Language Specification. If you mean something from the
java.util.concurrentpackage, such asSemaphore, this would be overkill; if you mean just plain JavaObjectinstances that you use as locks, that would be a simple and straightforward approach. Note, however, that you don’t really need any locking at all:volatilevariables would be enough, or, at most,AtomicLongs (or whatever type you use) for the two timestamp values, so you can update them atomically.