ThreadTest.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
|
package
main;
import
java.util.concurrent.atomic.AtomicLong;
import
net.jcip.annotations.GuardedBy;
import
net.jcip.annotations.ThreadSafe;
@ThreadSafe
public
class
ThreadTest {
private
long
hits1;
@GuardedBy
(
"this"
)
private
long
hits2;
private
final
AtomicLong count =
new
AtomicLong(
0
);
public
long
getCounts() {
return
count.get();
}
public
synchronized
long
getHits1() {
return
hits1;
}
public
synchronized
long
getHits2() {
return
hits2;
}
public
synchronized
void
IncreaseHits1() {
++hits1;
}
public
void
service(
int
n)
throws
InterruptedException {
for
(
int
i =
1
; i <= n; i++) {
new
Thread(
new
Runnable() {
@Override
public
void
run() {
// TODO Auto-generated method stub
synchronized
(
this
) {
++hits2;
}
IncreaseHits1();
count.incrementAndGet();
}
}).start();
}
System.err.println(
"All Threads running!"
);
Thread.currentThread().sleep(
2000
);
System.out.println(
"hits1:"
+ getHits1() +
" hits2:"
+ getHits2()
+
" AtomicLong:"
+ getCounts());
}
}
|
main.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package
main;
public
class
main {
public
static
void
main(String[] args)
throws
InterruptedException {
ThreadTest threadTest =
new
ThreadTest();
for
(
int
i =
0
; i <
1000
; i++) {
threadTest.service(
10000
);
}
}
}
|
请问,hits2是否最后的结果是否正确,是否线程安全?
当累计跑了185次service后,控制台输出为:
1
2
3
|
synchronized
(
this
) {
++hits2;
}
|
看输出结果的话,上面这这一小段同步块代码貌似并非是线程安全的。不了解java注解有什么作用如@ThreadSafe和@GuardedBy("this"),应该不会对运行结果造成什么影响吧。
本文转自 ponpon_ 51CTO博客,原文链接:http://blog.51cto.com/liuxp0827/1415563,如需转载请自行联系原作者