-
Notifications
You must be signed in to change notification settings - Fork 7
/
Synch1.java
56 lines (46 loc) · 1.19 KB
/
Synch1.java
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 chapter11;
//This program uses a synchronized blocks
class Callme2 {
public void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller2 implements Runnable {
String msg;
Callme2 target;
Thread t;
public Caller2(Callme2 trg, String s) {
target = trg;
msg = s;
t = new Thread(this);
}
public void run() {
synchronized (target) { //synchronized block
target.call(msg);
}
}
}
public class Synch1 {
public static void main(String[] args) {
Callme2 target = new Callme2();
Caller2 ob1 = new Caller2(target, "Hello");
Caller2 ob2 = new Caller2(target, "Synchronized");
Caller2 ob3 = new Caller2(target, "World");
ob1.t.start();
ob2.t.start();
ob3.t.start();
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
}