|
|
In Java, two threads can communicate by accessing a shared variable (shared-memory model). If two threads can both modify an object, that is, they can both execute a method that assigns to a shared variable, then the modifications must be synchronized. This is easy - just declare the method to be synchronized! This means that Java will ensure that only one thread executes the method at a time. When we employ synchronized methods, the scope of the lock is the execution time of these methods. This execution time, is sometimes referred to as the method scope. It should be noted, however, that the lock is based on a specific object and not on any particular method. Besides synchronization is based on actual objects, not references to objects We now look at the inner workings of synchronized methods vis-à-vis unsynchronized methods. In this context we have a message queue object to which two threads add and remove messages. We start off with having both the methods add() and remove() in the message queue as synchronized methods and then proceed to experiment with these methods. Source
JAR Files: Please refer to the Java-Basics section for more information on using JAR files. |