forked from liqiangit/Java8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynch.java
More file actions
59 lines (50 loc) · 1.02 KB
/
Copy pathSynch.java
File metadata and controls
59 lines (50 loc) · 1.02 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
57
58
59
package chapter11;
/**
* p253 使用同步方法 synchronized
* @author marsamoeba
*
*/
class Callme {
// 添加同步方法 保证资源同步
synchronized void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
e.printStackTrace();
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
@Override
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String[] args) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
e.printStackTrace();
}
}
}