它们是否是线程安全的

它们是否是线程安全的

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

问题描述

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

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 };
}

所以如果我有两个线程连续调用ths方法, (说大丹狗和公牛狗)和另一个与猫(说波斯和暹罗)我会得到猫和狗在同一阵列吗?

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 在这种情况下)也是线程安全的,因为一旦创建它们不能更改,所有线程看到相同的值。另一方面,如果方法是接受(可变)日期,则可能有问题。两个线程可以同时修改同一个对象实例,导致竞态条件和可见性问题。

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.

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

09-01 18:27