Java 同步代码块的疑问

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后,控制台输出为:

wKioL1N96FXDPN20AAF1dq37do0409.jpg


1
2
3
synchronized  ( this ) {
     ++hits2;
}

看输出结果的话,上面这这一小段同步块代码貌似并非是线程安全的。不了解java注解有什么作用如@ThreadSafe和@GuardedBy("this"),应该不会对运行结果造成什么影响吧。










本文转自 ponpon_ 51CTO博客,原文链接:http://blog.51cto.com/liuxp0827/1415563,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值