Saleh Feek wrote:The way these threads work (violates) the rule(s) that I understand about threads.
1- On a single processor machine only one thread can actually be running at a time
2- Each object in Java is said to have a lock.
3- A thread entering a synchronized method gains the lock on the object that contains the method
4- No other thread can access any synchronized method in that object until the lock is released - by thread completing the processing inside the method.
When the start() method is sent to both threads alphonse.bow(gaston) & gaston.bow(alphonse), they are both moved to the runnable state.
name the threads
Thread1: alphonse.bow(gaston)
Thread2: gaston.bow(alphonse)
If the selected thread say Thread1 by the processor to be moved to the running state is alphonse.bow(gaston), then it is running, and no other thread can start running until Thread1 completes the processing of the method bow() on alphonse object.
The processing steps is to print: bow() methode invoked on Alphonse object
Then sleep(50) - note that sleep() will not move Thread1 to the blocked state because the method is labelled with synchronized .
Finally invoke gaston.bowBack(alphonse)
Steve
Saleh Feek wrote:
A- Invoking a method of a particular object from several threads.
B- Invoking a method of different objects from several threads. (here, even if objects are of the same class)
In A, once a thread invokes a synchronized methods of a particular object, no other thread can invoke any synchronized method of that particular object, until that thread finishes processing that method of that particular object.
In B, if there are two objects of the same class say obj1 and obj2, and if one thread say thread1 invokes any synchronized method of obj1, another thread say thread2 can invoke any method of obj2, but cannot invoke any synchronized method of obj1 until thread1 finishes processing the synchronized method of obj1.
Don't get me started about those stupid light bulbs. |