Java中synchronized的使用实例
来源:才华咖 本文已影响2.22W人
来源:才华咖 本文已影响2.22W人
synchronized关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C、D等)正在用这个方法,若有则要等正在使用synchronized方法的线程B(或者C、D)运行完这个方法后再运行此线程A,若没有则直接运行。下面小编给大家介绍Java中synchronized的使用实例,欢迎阅读!
Java中synchronized的使用实例一、使用场景
在负责后台开发的.时候,很多时候都是提供接口给前端开发人员去调用,会遇到这样的场景:
需要提供一个领奖接口,每个用户名只能领取一次,我们可以将成功领取的用户在数据库用个标记保存起来。如果这个用户再来领取的时候,查询数据库看该用户是否领取过。
但是问题来了,假设用户手速很快,极短时间内点了两次领奖按钮(前端没有进行控制,我们也不能依赖前端去控制)。那么可能掉了两次领奖接口,而且有可能第二次调用的时候查询数据库的时候,第一次领奖还没有执行完成更新领奖标记。
这种场景就可以使用到synchronized
二、使用实例
代码:
运行结果:
从结果来看,可知道,synchronized起作用了,这里调用了两次syn(String userName)方法,期间设置其停留5秒,但是还是等第一次执行完,第二次调用才进入synchronized块里面的。
为了进一步确认我们的假设,我们不防把synchronized去掉如下:
运行结果:
对比即可分析出来了
使用方式从实例可看出来:
用synchronized把代码括起来。
JavaScript在Android的WebView中parseInt函数转换不正确
java使用ConcurrentHashMap和计数器实现锁的方法
中学英语have and eye on,have an eye to,have an eye for这三
初中英语写作范文:My Happy Times During Winter Vacation
Travels on Holidays in China 英语作文
AndroidApp中使用SurfaceView制作多线程动画的实例讲解
jQuery中的read和JavaScript中的onload函数的区别在哪
英语阅读:African Union Leaders Talk Mali, Chinese Investmen
Fancy the original or movie ones大学英语作文
Should Private Cars Be Encouraged in China高中英语作文
英语作文Travels On Holidaysin China
关于javascript中encodeURI和decodeURI的使用方法
A Lifeguard at Johns Beach Saved a Drowning Child,A Lifeguar英语作文
JavaScript中创建字典对象(dictionary)的实例
My Happy Times During Winter Vacation初中英语作文
java script remove Child的使用注意事项
美文欣赏:Neanderthal Diners Had Side of Veggies
使用果实累累造句的例子
中学生英语作文:Cure Sadness with Company
A Letter to Univsity Pesident about the Canteen Service on C
The relationship between theory and practice大学英语作文
Too many essential for children to learn英语作文
Modern Technology Makes Life More Conv英语六级作文
英语作文:I thinh you can be good friends
JAVA面试中的陷阱
VOA的慢速英语听力文摘:Mystery at The Ice Castle Inn
高中英语作文:My approach to difficulties in learning
The place of Science and Technology in Modern Life英语作文
八年级Unit 5 What were you doing when the rainstorm came?教学设计
英语材料阅读:with mental and physical disorders
浅析javascript中function 的length属性
英语美文:Olympic Fund Scratchcard Launched
Linux Mint Cinnamon下使用vino-server配置桌面共享的方法
英语Lesson8家庭作业:Dannys favourite colour
Traditions of Chinese New Year为题目的作文
奥运英语作文:中国跳水队(Diving into Gold: Chinas Dream Team
八年级《unit8 Why don’t you get her a scarf? Period1》评课稿
示波器的使用实验报告(实用6篇)
私家车的坏处The Disadvantages of Private Cars英语作文
在java中Synchronized的用法