These tips and cautions will help you write better programs and save you from agonizing over why the compiler produces error messages.
setPriority(int priority) or yield()? Both methods affect threads similarly. However, setPriority(int priority) offers flexibility, whereas yield() offers simplicity. Also, yield() might immediately reschedule the yielding thread, which accomplishes nothing. I prefer setPriority(int priority), but you must make your own choice.
notify() in the ProdCons2 program because only one thread waits for a condition to occur. In your programs, where more than one thread might simultaneously
wait for the same condition to occur, consider using notifyAll(). That way, no waiting thread waits indefinitely.
wait() or notify() from outside a synchronized context, either call results in an IllegalMonitorStateException.
The source code to the article's ProdCons2 application reveals my use of an if decision statement instead of a loop statement (such as while) to test the writeable condition variable. For example, in ProdCons2's Shared class, you encounter if in the following setSharedChar(char c) method:
synchronized void setSharedChar (char c)
{
if (!writeable)
try
{
wait ();
}
catch (InterruptedException e) {}
this.c = c;
writeable = false;
notify ();
}
Various developers oppose the use of if to test condition variables. Instead, they argue in support of loops. By following their advice, the previous method transforms
into the following method:
synchronized void setSharedChar (char c)
{
while (!writeable)
try
{
wait ();
}
catch (InterruptedException e) {}
this.c = c;
writeable = false;
notify ();
}
Is it better to use if or a loop (such as while)? For ProdCons2, either approach is fine—because I've carefully coded my programs to ensure that a thread sets the appropriate condition
variable (on which another thread waits) prior to waking that thread. For complex programs, where you are uncertain that a
waiting thread's condition variable will be set to an appropriate value prior to waking that thread, you should use a loop.
That way, the just-woken thread can retest its condition variable and wait if that variable contains the wrong value.
Please complete the following exercise:
Many computer science textbooks introduce the bounded buffer problem—a classic computer science problem that teaches the concept of monitors. According to the bounded buffer problem, a writer thread produces multiple data items stored in a fixed-size memory buffer. When that buffer fills, the writer thread waits. The reader thread notifies the writer thread when the buffer empties. Conversely, the reader thread retrieves data items from the memory buffer. When that buffer empties, the reader thread waits. The writer thread notifies the reader thread when the buffer fills.
The following BB.java source code demonstrates the bounded buffer problem. However, there is a catch. I omitted the source code to the Buffer class. Your job is to complete this program by supplying appropriate code. Make sure to use the wait() and notify() methods:
// BB.java
class BB
{
public static void main (String [] args)
{
Buffer buffer = new Buffer (5); // Buffer holds a maximum of 5 characters
new Writer (buffer).start ();
new Reader (buffer).start ();
}
}
class Buffer
{
// Supply appropriate code in this class
}
class Writer extends Thread
{
private Buffer buffer;
Writer (Buffer buffer)
{
this.buffer = buffer;
}
public void run ()
{
for (int i = 0; i < 26; i++)
buffer.put ((char) ('A' + i));
for (int i = 0; i < 26; i++)
buffer.put ((char) ('a' + i));
for (int i = 0; i < 10; i++)
buffer.put ((char) ('0' + i));
buffer.put ('*'); // Indicate end of data items
}
}
class Reader extends Thread
{
private Buffer buffer;
Reader (Buffer buffer)
{
this.buffer = buffer;
}
public void run ()
{
char c;
while ((c = buffer.get ()) != '*')
System.out.print (c);
System.out.print ('\n');
}
}
Once you finish writing and compiling the code, run the program. You should see the following output:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
Last month, I asked you two questions and gave you a program to write. My answers appear in red.