I am trying to ensure that only one
thread can access the method(s) of an object at a time
without using the keyword synchronized. I am a newbie to CS/IT , so i dont know if this will be easy to implement. I know small bits of information about computers and just
java (
Thats all !) . Please tell me if i need more knowledge to make such a program. If it can be implemented easily, please give me hints and suggestions. Am i doing something foolish ? Please let me know.
A small description :
ThreadSafe class - any class that extends this will be able to check if some thread has acquired a lock on it and let its instance be accessed by one thread at a time.
The checkOwner() is used to control the access to the methods of subclasses.
The release() is invoked by a thread to show that it has released the lock on an object.
Room extends ThreadSafe - this has a only a method to show which "Sleeper" thread is accessing this Room.
Sleeper extends Thread - this has reference to a Room object and simply runs the
useRoom() method of a Room instance.
LockSimulator class - has the
main() method. It creates 5
Sleepers with unique names and a reference/key to the same
Room object. And as per my goal, only one Sleeper can use a Room at a time. Others have to wait till the current sleeper releases the room.
Here is the working code of my failed simulator :
You can run this and get unpredictable output...here is a sample :