Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux集群 > Architecture > » 正文

Lock与synchronized 的区别(2)

来源: 未知 分享至:
@Override
  • /**
  • * synchronized关键字不在方法签名里面,所以不涉及重载问题
  • */
  • synchronized long getValue() {
  • return super.countValue;
  • }
  • @Override
  • synchronized void sumValue() {
  • super.countValue+=preInit[index++%round];
  • }
  • }
  •  
  •  
  • class LockTest extends TestTemplate{
  • ReentrantLock lock=new ReentrantLock();
  • public LockTest(String _id,int _round,int _threadNum,CyclicBarrier _cb){
  • super( _id, _round, _threadNum, _cb);
  • }
  • /**
  • * synchronized关键字不在方法签名里面,所以不涉及重载问题
  • */
  • @Override
  • long getValue() {
  • try{
  • lock.lock();
  • return super.countValue;
  • }finally{
  • lock.unlock();
  • }
  • }
  • @Override
  • void sumValue() {
  • try{
  • lock.lock();
  • super.countValue+=preInit[index++%round];
  • }finally{
  • lock.unlock();
  • }
  • }
  • }
  •  
  •  
  • class AtomicTest extends TestTemplate{
  • public AtomicTest(String _id,int _round,int _threadNum,CyclicBarrier _cb){
  • super( _id, _round, _threadNum, _cb);
  • }
  • @Override
  • /**
  • * synchronized关键字不在方法签名里面,所以不涉及重载问题
  • */
  • long getValue() {
  • return super.countValueAtmoic.get();
  • }
  • @Override
  • void sumValue() {
  • super.countValueAtmoic.addAndGet(super.preInit[indexAtomic.get()%round]);
  • }
  • }
  • abstract class TestTemplate{
  • private String id;
  • protected int round;
  • private int threadNum;
  • protected long countValue;
  • protected AtomicLong countValueAtmoic=new AtomicLong(0);
  • protected int[] preInit;
  • protected int index;
  • protected AtomicInteger indexAtomic=new AtomicInteger(0);
  • Random r=new Random(47);
  • //任务栅栏,同批任务,先到达wait的任务挂起,一直等到全部任务到达制定的wait地点后,才能全部唤醒,继续执行
  • private CyclicBarrier cb;
  • public TestTemplate(String _id,int _round,int _threadNum,CyclicBarrier _cb){
  • this.id=_id;
  • this.round=_round;

  • Tags:
    分享至:
    最新图文资讯
    1 2 3 4 5 6
    验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
    关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史