-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncBlockExample.java
More file actions
45 lines (39 loc) · 1.14 KB
/
SyncBlockExample.java
File metadata and controls
45 lines (39 loc) · 1.14 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
package example.ThreadExample;
/**
* 同步
* - Process synchronization
* - Thread synchronization
* - 相互排斥 mutual exclusive
* - 同步方法 sync method
* - 同步區塊 sync block
* - 靜態同步 static sync
* - 執行緒間的通信 inter-thread communication
*/
public class SyncBlockExample {
public static void main(String[] args) {
// example for sync block.
exampleWithSyncBlock();
}
public static void exampleWithSyncBlock() {
DemoSyncBlock demo = new DemoSyncBlock();
JobThreadFirst jt1 = new JobThreadFirst(demo);
JobThreadSecond jt2 = new JobThreadSecond(demo);
jt1.start();
jt2.start();
}
}
class DemoSyncBlock extends DemoProblemWithoutSync {
public void printDemo(int n) {
//! sync block.
synchronized(this) {
for (int i=1; i<=5; i++) {
System.out.println("output: " + i*n);
try {
Thread.sleep(500);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
}