加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么算得少甚至使用synchronized关键字?

发布时间:2020-12-15 05:07:57 所属栏目:Java 来源:网络整理
导读:我开始学习一些使用的 java并发概念. 但是这段代码之一超出了我的理解范围. public class Count { private int count = 0; public synchronized void setCount(int count) { this.count = count; } public synchronized int getCount() { return count; } }
我开始学习一些使用的 java并发概念.
但是这段代码之一超出了我的理解范围.

public class Count { 
    private int count = 0; 
    public synchronized void setCount(int count) { 
        this.count = count; 
    } 
    public synchronized int getCount() { 
        return count; 
    } 
} 
class CountRunner extends Thread { 
    Count count; 
    public CountRunner(Count count) { 
        this.count = count; 
    } 
    public void run() { 
        for (int i = 1; i <= 1000; i++) { 
            count.setCount(count.getCount() + 1); 
        } 
    } 
} 
class TestCount { 
    public static void main(String[] args) throws Exception { 
        Count count = new Count(); 
        CountRunner runnerA = new CountRunner(count); 
        CountRunner runnerB = new CountRunner(count); 
        runnerA.start(); 
        runnerB.start();         
        runnerA.join(); //join statement here 
        runnerB.join(); 
        System.out.println("count.getCount = " + count.getCount()); 
    } 
}
Question:
1. The result is a little less than 2000 for many times,why ?
2. if delete 2 join() statement,why count.getCount = 451,even less ?
3. i think there will be no effect of deleting the join() statements,because i already have Synchronized method to lock one object to one thread each time ? 
So,What's the point of using Synchronized and join() ?

解决方法

这很简单.通过调用getCount来调用setCount方法1.在输入方法之前,运行时会计算getCount(synchronized),但是在离开getCount并输入setCount并且其他线程可以输入调用getCount时,您不会保持锁定.因此,每隔两次(或更多,取决于您创建的线程数)线程将在getCount中具有相同的值.想象一下,线程A在getCount中输入并接收值1.运行时产生它执行到胎面B,它调用getCount并接收相同的值1.线程B将值设置为1并再次运行50次,因此在该阶段您的计数将为50.运行时产生执行到线程A,线程A调用setCount为1(记住它没有设法调用setCount并产生它的exec).现在A将值设置为1(这是错误的).

改变你运行这样的实现:

public void run() { 
    for (int i = 1; i <= 1000; i++) {
      synchronized(count){ 
        count.setCount(count.getCount() + 1); 
      }
    } 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读