Help: Synchronized Statements


Help is available for each task, or you can go straight to the solution source code.

Task 1

Create a Speaker class that extends Thread and as its task repeatedly makes calls to the announce method of AnnounceBox to say a sentence, one call for each word. The code in the SynchStmtApplet suggests the necessary interface for the Speaker class. Do not attempt synchronization. In order to maximize the chance of contention between two Speakers, have them sleep for a small random amount of time after completing the sentence. Each Speaker should try to say its sentence five times.
The constructor for the Speaker class should take an AnnounceBox and an array of Strings and store them in local variables. It's run method iterates through that array, repeatedly calling the announce method on the given AnnounceBox for each entry.

Task 2

Compile and run the applet to demonstrate contention for the AnnounceBox.
Compile the applet using javac and run it using the appletViewer. Examine the output for garbling of the two sentences.

Task 3

Change the Speaker class to synchronize on the AnnounceBox before writing to it using a synchronized statement.
In the run method, before making calls to the announce method, add a statement to synchronize on the AnnounceBox, making sure to release it after a complete sentence is entered.

Task 4

Compile and run the applet, both sentences should be uninterrupted. AnnounceBox.
Compile the applet using javac and run it using the appletViewer.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.