Java中的方法参数是否安全? [英] Are method parameters thread safe in Java?

查看:129
本文介绍了Java中的方法参数是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class Shared{    
     public void sharedMethod(Object o){
          //does something to Object
     }     
}

//this is how threads call the shared method
run(){
     sharedInstance.sharedMethod(someObject);
}

现在 o 正作为参数传递给方法。多个线程并行调用相同的方法。我们可以安全地说这个代码是线程安全的吗?

Now the o is being passed as the parameter to the method. And the same method is being called by multiple threads in parallel. Can we safely say that this code is thread safe?

有两种情况:


  • 如果在线程之间共享 someObject

  • 如果每个线程都有自己的副本someObject

  • If the someObject is being shared among the threads
  • If every Thread has its own copy of someObject

推荐答案

不,你不能这么说。方法参数是线程的本地参数,这意味着每个参数都有自己的 o 引用变量的副本,但是如果你用多个线程中的同一个对象调用这个方法,那么参数将在它们之间共享(请记住,Java是按值传递)。在这种情况下,您需要提供显式同步以避免麻烦。

No you cannot say that. Method parameters are local to threads, meaning each one has their own copy of the o reference variable, But if you call this method with the same object from multiple threads, then the argument will be shared between them (remember that Java is pass-by-value). In that case, you need to provide explicit synchronization to avoid troubles.

这篇关于Java中的方法参数是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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