Java Reference
In-Depth Information
More on Blocking
Blocking is an important phenomenon in threading and thus deserves a few more words of
explanation. To quickly review, blocking threads do not use CPU cycles and are in a state of
suspended animation. They do not wait for a time period to expire, but rather for an event to
occur; specifically, a lock they were trying to acquire becomes available. Blocking threads
deserve a healthy dose of respect because they do not release locked resources when they slice
out of the CPU. A blocking thread that does not receive its lock can refuse to release resources
that other threads might need, in addition to never coming out of hibernation, as shown in
Listing 4-12. Figure 4-12 shows the output of this example.
Listing 4-12. Blocking Example
1 import java.net.*;
2
3 public class BlockingExample extends Thread {
4 private static Object mylock = new Object();
5
6 public static void main(String args[]) throws Exception {
7 LockOwner lo = new LockOwner();
8 lo.setName("Lock owner");
9 lo.start();
10
11 // Wait for a little while for the lock owner thread to start
12 Thread.sleep(200);
13
14 // Now start the thread that will be blocked
15 BlockingExample be = new BlockingExample();
16 be.setName("Blocked thread");
17 be.start();
18
19 // Wait for a little while for the blocked thread to start
20 Thread.sleep(200);
21
22 // Now print the two threads states
23 printState(lo);
24 printState(be);
25 }
26
27 // start a thread.
28 public void run() {
29 // wait for the mylock object to be freed,
30 // which will never happen
31 synchronized (mylock) {
32 System.out.println(getName() + " owns lock");
33 System.out.println("doing Stuff");
34 }
Search WWH ::




Custom Search