【问题标题】:Two threads calling an increment method synchronized on "this" elasped time lower than expected两个调用增量方法的线程在“此”经过的时间上同步,低于预期
【发布时间】:2017-02-14 04:19:38
【问题描述】:

计数为:20000 经过时间:5001

当我输入以下代码时,我得到了这个结果,我有一个类有一个计数变量,它在“this”的同步块中递增,为什么当我在 main 和 2 个线程中创建一个新的锻炼对象时使用 2 anon runnable 的调用 ex.increment 是否只需要 5 秒?总共不应该是 10 秒,因为一个线程获得了锁并且它在工作而另一个应该等待吗?我得到了同步的想法,但我很困惑为什么如果我要让练习实现可运行并将其传递给 Thread() 构造函数,这将需要 10 秒,但不是这样,请解释一下,谢谢。

public class Exercise {
    private int count = 0;

    public int getCount() {
        return count;
    }

    public void increment() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (this) {
            for (int i = 0; i < 10000; i++) {
                count++;
            }
        }
    }
}

public class App {
    public static void main(String[] args) {
        Exercise ex = new Exercise();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                ex.increment();
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                ex.increment();
            }
        });

        long start = System.currentTimeMillis();

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();

        System.out.println("Count is: " + ex.getCount() + " Time elapsed: " + (end - start));
    }
}

【问题讨论】:

  • 何时获取锁?在sleep 之前还是之后?换句话说,sleep 调用是同时执行还是一个接一个地执行?
  • 等等,你的意思是方法同时休眠 5 秒,而同步块实际上在这 5 秒之外彼此串行执行?
  • 他们有什么理由相互等待?
  • 当我阅读您的评论时,我将 sleep 放在同步块中并得到 10 秒,我想我现在理解了,我在没有同步块的情况下尝试了 AtomicInteger 并得到了 5 秒,谢谢。

标签: java multithreading


【解决方案1】:

两个线程几乎并行休眠 5 秒。

然后一些线程进入同步块并立即运行循环。然后另一个线程做同样的事情。

这里没有什么令人惊讶的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多