Repository navigation
Expand file tree
/
Copy pathRun10_synBlockMoreObjectOneLock.java
More file actions
95 lines (82 loc) · 2.21 KB
/
Copy pathRun10_synBlockMoreObjectOneLock.java
File metadata and controls
95 lines (82 loc) · 2.21 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.brianway.learning.java.multithread.synchronize.example10;
/**
* Created by brian on 2016/4/13.
*/
/**
* P101
* 验证同步synchronized(class)代码块的作用
* 顺便验证了下static方法是不能复写的
*
* @see ServiceSub,ServiceSub2
*/
public class Run10_synBlockMoreObjectOneLock {
public static void main(String[] args) {
//testSub();
//testSub2();
testBlock();
}
/**
* 验证同步sychronized(class)代码块的作用
*/
public static void testBlock() {
final ServiceSub service1 = new ServiceSub();
final ServiceSub service2 = new ServiceSub();
Thread a = new Thread() {
@Override
public void run() {
service1.printA();
}
};
a.setName("A");
a.start();
Thread b = new Thread() {
@Override
public void run() {
service2.printB();
}
};
b.setName("B");
b.start();
}
/**
* testSub断点调试结果是运行的Service类的printA方法
*/
public static void testSub() {
ServiceSub service1 = new ServiceSub();
ServiceSub service2 = new ServiceSub();
ThreadA a = new ThreadA(service1);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service2);
b.setName("B");
b.start();
}
/**
* testSub2断点调试结果是运行的Service类的printA方法
*/
public static void testSub2() {
ServiceSub2 service1 = new ServiceSub2();
ServiceSub2 service2 = new ServiceSub2();
ThreadA a = new ThreadA(service1);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service2);
b.setName("B");
b.start();
}
}
/*
输出:
In ServiceSub
线程名:A 在 1460480421944进入printA
线程名:A 在 1460480423944离开printA
线程名:B 在 1460480423944进入printB
线程名:B 在 1460480423944离开printB
---------
也可能:
线程名:B 在 1460480476089进入printB
线程名:B 在 1460480476089离开printB
In ServiceSub
线程名:A 在 1460480476089进入printA
线程名:A 在 1460480478089离开printA
*/