如果非同步静态方法不修改静态类变量,它们是否线程安全? [英] Are non-synchronised static methods thread safe if they don't modify static class variables?

查看:17
本文介绍了如果非同步静态方法不修改静态类变量,它们是否线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道您是否有一个同步的静态方法,但是修改任何静态变量是否是线程安全的?如果该方法在其中创建局部变量呢?例如,下面的代码是线程安全的吗?

I was wondering if you have a static method that is not synchronised, but does not modify any static variables is it thread-safe? What about if the method creates local variables inside it? For example, is the following code thread-safe?

public static String[] makeStringArray( String a, String b ){
    return new String[]{ a, b };
}

因此,如果我有两个线程连续并发地调用该方法,一个是狗(比如大丹犬"和斗牛犬"),另一个是猫(比如波斯"和暹罗"),我会得到猫和狗在同一个数组中?或者猫和狗永远不会同时在同一个方法调用中?

So if I have two threads calling ths method continously and concurrently, one with dogs (say "great dane" and "bull dog") and the other with cats (say "persian" and "siamese") will I ever get cats and dogs in the same array? Or will the cats and dogs never be inside the same invocation of the method at the same time?

推荐答案

这个方法是 100% 线程安全的,即使它不是 static 也是如此.当您需要在线程之间共享数据时,就会出现线程安全问题——您必须注意原子性、可见性等.

This method is 100% thread safe, it would be even if it wasn't static. The problem with thread-safety arises when you need to share data between threads - you must take care of atomicity, visibility, etc.

该方法只对参数进行操作,这些参数驻留在栈中和对堆上不可变对象的引用.堆栈本质上是线程本地的,因此永远不会发生数据共享.

This method only operates on parameters, which reside on stack and references to immutable objects on heap. Stack is inherently local to the thread, so no sharing of data occurs, ever.

不可变对象(在本例中为String)也是线程安全的,因为一旦创建它们就无法更改并且所有线程看到相同的值.另一方面,如果该方法接受(可变)Date,您可能会遇到问题.两个线程可以同时修改同一个对象实例,从而导致竞争条件和可见性问题.

Immutable objects (String in this case) are also thread-safe because once created they can't be changed and all threads see the same value. On the other hand if the method was accepting (mutable) Date you could have had a problem. Two threads can simultaneously modify that same object instance, causing race conditions and visibility problems.

这篇关于如果非同步静态方法不修改静态类变量,它们是否线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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