艾尚格莱美,7t7t,读你简谱
在多线程对一个整数进行自增操作时,需要用synchronized进行同步。然而,如果synchronized的对象选取的不合适的话,就无法实现同步的效果。如下面的例子。
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对象一直处于改变当中,起不到两个线程的锁的作用。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论