The output may well look like this:
Did
Did
DidNot
DidNot
If each thread yields after each println, other printing threads will have a chance to run. Suppose we set
doYield to true with an invocation such as this:
Babble true 2 Did DidNot
The yields give the other threads a chance to run, and the other threads will yield in turn, producing an output
more like this:
Did
DidNot
DidNot
Did
The output shown is only approximateperhaps you expected the words to alternate? A different thread
implementation could give different results, or the same implementation might give different results on
different runs of the application. But under all implementations, invoking yield can give other threads a
more equitable chance at getting cycles.
Two other factors affect the behavior of this program (and many like it that try to demonstrate scheduling
behavior). The first is that println uses synchronization, so the different threads must all contend for the
same lock.
The second factor is that there are three threads in the program, not two. The main thread has to create and
start the two Babble tHReads and that means that it contends with them for scheduling as well. It is entirely
possible that the first Babble tHRead will run to completion before the main thread even gets the chance to
create a second Babble tHRead.
Exercise 14.7: Run Babble multiple times and examine the output: Is it always the same? If possible, run it
on different systems and compare.
14.7. Deadlocks
Whenever you have two threads and two objects with locks, you can have a deadlock, in which each thread
has the lock on one of the objects and is waiting for the lock on the other object. If object X has a
synchronized method that invokes a synchronized method on object Y, which in turn has a
synchronized method invoking a synchronized method on object X, two threads may wait for each
other to complete in order to get a lock, and neither thread will be able to run. This situation is also called a
deadly embrace. Here's a Friendly class in which one friend, upon being hugged, insists on hugging back: