-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirtyRead.java
More file actions
56 lines (43 loc) · 1.16 KB
/
Copy pathDirtyRead.java
File metadata and controls
56 lines (43 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package threadbook.ch07;
public class DirtyRead extends Object {
private String fname;
private String lname;
public String getNames() {
return lname + ", " + fname;
}
public synchronized void setNames(
String firstName,
String lastName
) {
print("entering setNames()");
fname = firstName;
try { Thread.sleep(1000); }
catch ( InterruptedException x ) { }
lname = lastName;
print("leaving setNames() - " + lname + ", " + fname);
}
public static void print(String msg) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ": " + msg);
}
public static void main(String[] args) {
final DirtyRead dr = new DirtyRead();
dr.setNames("George", "Washington"); // initially
Runnable runA = new Runnable() {
public void run() {
dr.setNames("Abe", "Lincoln");
}
};
Thread threadA = new Thread(runA, "threadA");
threadA.start();
try { Thread.sleep(200); }
catch ( InterruptedException x ) { }
Runnable runB = new Runnable() {
public void run() {
print("getNames()=" + dr.getNames());
}
};
Thread threadB = new Thread(runB, "threadB");
threadB.start();
}
}