Java Reference
In-Depth Information
IceCreamMan.java Example
The
IceCreamMan
object starts a loop inside his
run
method. The method checks to see if any
IceCreamDish
objects need to be serviced. This all happens in the
run
method between lines
15 and 32:
1 import java.util.*;
2
3 public class IceCreamMan extends Thread {
4 /**
5 * a list to hold the IceCreamDish objects
6 */
7 private List<IceCreamDish> dishes = new ArrayList<IceCreamDish> ();
8
9 /**
10 * Start a thread that waits for ice cream bowls to be given to it.
11 */
12 String clientExists = "IceCreamMan: has a client";
13 String clientDoesntExist = "IceCreamMan: does not have a client";
14
15 public void run() {
16 while (true) {
17 if (!dishes.isEmpty()) {
18 System.out.println(clientExists);
19 serveIceCream();
20 } else {
21 try {
22 System.out.println(clientDoesntExist);
23 // sleep, so that children have a chance to add their
24 // dishes. see note in topic about why this is not a
25 // yield statement.
26 sleep(1000);
27 } catch(InterruptedException ie) {
28 ie.printStackTrace();
29 }
30 }
31 }
32 }
Line 16 starts an infinite loop for this thread. Remember that the thread for the
IceCreamMan
is a daemon thread, so even though this is an infinite loop it will not stop the
application from exiting once all
Child
threads have eaten their ice cream.
Line 17 checks to see if any
IceCreamDish
objects have been queued up for processing. If
not, the
IceCreamMan
thread sleeps for a second and then checks again, per lines 22 through
26. If the queue has an entry, then the
IceCreamMan
thread calls the
serveIceCream
method.
At line 26 we had a choice—we could have
yield
ed to other threads, or we could
sleep
for some time. Either choice would have provided the
Child
threads a chance to run. However,
sleeping provides a better chance for the
Child
threads to run, as the JVM knows that the
IceCreamMan
will not be running for at least a second—if we had yielded, any of the
Child