好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

关于synchronized有趣的同步问题

在多线程对一个整数进行自增操作时,需要用 synchronized 进行 同步 。然而,如果synchronized的对象选取的不合适的话,就无法实现同步的效果。如下面的例子。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

public class syncthreadtest extends thread {

   public static integer count = 0 ;

   private static final int times = 10000 ;

   public syncthreadtest(){

     super ( "syncthread" );

   }

   @override

   public void run(){

     synchronized (count){

       for ( int i = 0 ; i < times; i ++){

         count++;

       }

     }

   }

   public static void main(string[] args) throws interruptedexception{

     syncthreadtest t1 = new syncthreadtest();

     syncthreadtest t2 = new syncthreadtest();

     t1.start();

     t2.start();

     t1.join();

     t2.join();

     system.out.println(count);

   }

}

在上面的例子中,选取了自增的变量作为同步的对象。启动2个线程,各自对count自增10000次。最后的结果,count的值却不是20000次。

原因在于count对象一直处于改变当中,起不到两个线程的锁的作用。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/li_canhui/article/details/83108478

查看更多关于关于synchronized有趣的同步问题的详细内容...

  阅读:8次