Java Reference
In-Depth Information
6 //create two runners
7 Runner johnson = rce.new Runner("Johnson");
8 Runner smith = rce.new Runner("smith");
9
10 //point both runners to the same resource
11 smith.server = "the common object";
12 johnson.server = smith.server;
13
14 //start the race, based on a random factor, one thread
15 //or the other gets to start first.
16 if (Math.random() > .5) {
17 johnson.start();
18 smith.start();
19 } else {
20 smith.start();
21 johnson.start();
22 }
23 }
24
25 /**
26 * Creates a thread, then races for the resource
27 */
28 class Runner extends Thread {
29 public Object server;
30
31 public Runner(String name) {
32 super(name);
33 }
34
35 public void run() {
36 System.out.println(getName() + ": trying for lock on " + server);
37 synchronized (server) {
38 System.out.println(getName() + ": has lock on " + server);
39 // wait 2 seconds: show the other thread really is blocked
40 try {
41 Thread.sleep(2000);
42 } catch (InterruptedException ie) {
43 ie.printStackTrace();
44 }
45 System.out.println(getName() + ": releasing lock ");
46 }
47 }
48 }
49 }
Search WWH ::




Custom Search