Java同步差异线程 [英] Java synchronized difference threading

查看:91
本文介绍了Java同步差异线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:



同步功能和同步块之间有什么区别?

我不明白这两个线程代码之间的区别我相信这是相互的排除,但我不知道你有什么区别可以帮助我吗?

i dont understand the difference between these 2 codes for threading i believe it is for mutual exclusion but i dont understqnd whats the difference can you help me?

public synchronized void Method1 () {
  }

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

感谢您的帮助。

推荐答案

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

The only difference is reducing a number of operations guarded by a lock which can improve performance much.

示例:让我们假设我们有一个servlet给出一个输入中有大量因子的数组,我们想要计算servlet的启动频率。问题是同步对状态变量的访问 requestsCount

Example: let's imagine we have a servlet which gives an array of factors of a big number on input, and we want to count how often the servlet is launched. The problem is synchronizing the access to the state variable 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 Concurrency in Practice(第2章)中阅读了一个非常好的解释。我强烈建议您从封面到封面阅读本书。

UPD: you can read a very good explanation in a masterpiece "Java Concurrency in Practice" (chapter 2). I highly recommend to read this book from cover to cover.

这篇关于Java同步差异线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆