-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCorruptWrite.java
More file actions
56 lines (44 loc) · 1.28 KB
/
Copy pathCorruptWrite.java
File metadata and controls
56 lines (44 loc) · 1.28 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 CorruptWrite extends Object {
private String fname;
private String lname;
public void setNames(String firstName, String lastName) {
print("entering setNames()");
fname = firstName;
// A thread might be swapped out here, and may stay
// out for a varying amount of time. The different
// sleep times exaggerate this.
if ( fname.length() < 5 ) {
try { Thread.sleep(1000); }
catch ( InterruptedException x ) { }
} else {
try { Thread.sleep(2000); }
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 CorruptWrite cw = new CorruptWrite();
Runnable runA = new Runnable() {
public void run() {
cw.setNames("George", "Washington");
}
};
Thread threadA = new Thread(runA, "threadA");
threadA.start();
try { Thread.sleep(200); }
catch ( InterruptedException x ) { }
Runnable runB = new Runnable() {
public void run() {
cw.setNames("Abe", "Lincoln");
}
};
Thread threadB = new Thread(runB, "threadB");
threadB.start();
}
}