THE UNIVERSITY OF WESTERN AUSTRALIA

Department of Computer Science

230.304 CONCURRENT PROGRAMMING

Laboratory Sheet 3 (for laboratories during week 5)

The purpose of this laboratory is to :

Synchronizing Threads

Till now, our threads have executed at their own will or, rather at the will of the scheduler. However, as you have seen in the lectures, you may need to coordinate the access of multiple threads to shared objects in your program. Java allows you to coordinate the actions of multiple threads using synchronized methods and synchronized statements.Here is how it is done. You may not understand the following description completely, but it will be clear when we discuss monitors in the lectures. You should now follow the example program to understand the language features used in synchronizing threads.

The synchronized methods are declared with the synchronized keyword. Only one synchronized method can be invoked for an object at a given point. This prevents synchronized methods from multiple objects from conflicting with each other.

All classes and objects are associated with a unique monitor. The monitor associated with an object is used to control the way in which synchronized methods access the class or object. When a synchronized method is invoked for an object, it is said to acquire the monitor for that object. No other synchronized method can be invoked for that object until the monitor is released. A monitor is automatically realeased when the execution of the method is complete or when the synchronized method executes a method like wait(). In the second case, the thread associated with the currently executing synchronized method becomes not runnable until the wait condition is satisfied and no other method has acquired the object's monitor.

Here is an example program for synchronizing the execution of two threads. This is based on the Example1.java program in lab1. Here is some explanation of the program.

Java Concurrency Constructs

The following are the concurrency constructs and support in the Java language. Though this list is quite small, it is possible to write a wide range of concurrent programs with these constructs.

Waiting and Notification

Tasks

Amitava Datta
March, 2000