gpt4 book ai didi

java - 这个同步块(synchronized block)是否需要?

转载 作者:行者123 更新时间:2023-12-02 07:16:15 28 4
gpt4 key购买 nike

对于多线程环境中的这段代码,是否需要使用synchronized(c)?

SynchronizedCounter c = new SynchronizedCounter();
synchronized(c){
c.increment();
c.value();
}

public class SynchronizedCounter {
private int c = 0;

public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}

最佳答案

如果您想确保在 c.increment(); 之后调用 c.value() 时,这是需要的正在获取值 + 1

避免在调用c.increment()之间有另一个thread2调用c.decrement()的情况thread1

中的 c.value()

关于java - 这个同步块(synchronized block)是否需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14916400/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com