gpt4 book ai didi

Java同步差异线程

转载 作者:行者123 更新时间:2023-12-02 00:25:13 25 4
gpt4 key购买 nike

Possible Duplicate:
What is the difference between a synchronized method and synchronized block in Java?
What is the difference between a synchronized function and synchronized block?

我不明白这两个线程代码之间的区别,我相信这是为了互斥,但我不明白有什么区别,你能帮助我吗?

public synchronized void Method1 () {
}

public myFunction (){
synchronized (this) {
}
}

感谢您的帮助。

最佳答案

唯一的区别是减少了由锁保护的操作数量,这可以大大提高性能。

示例:假设我们有一个 servlet,它在输入中给出一系列大数字的因子,并且我们想要计算 servlet 的启动频率。问题在于同步对状态变量 requestsCount

的访问
//Poor performance
class PoorFactorizer implements Servlet {
private int requestsCount = 0;
public synchronized void service(ServletRequest req, ServletResponse res) {
BigInteger numberToFactorize = extractFromRequest(req);
BigInteger[] factors = factorize(numberToFactorize); // long lasting
// operation makes everyone wait
requestCount++;
encodeResponse(res, factors);
}
}

//Better perfomance
class PoorFactorizer implements Servlet {
private int requestsCount = 0;
public void service(ServletRequest req, ServletResponse res) {
BigInteger numberToFactorize = extractFromRequest(req);
BigInteger[] factors = factorize(numberToFactorize);
// since we need to guard only the class' state
// let's guard only the operation with the state
synchronized(this) {
requestCount++;
}
encodeResponse(res, factors);
}
}

UPD:你可以在一本杰作《Java并发实践》(第2章)中读到非常好的解释。我强烈建议您从头到尾阅读这本书。

关于Java同步差异线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10185867/

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