本文介绍了仅具有局部变量的实例方法的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,同时调用使用局部变量的实例方法是否仅与线程安全有关?

Generally, does simultaneously calling instance methods that use local variables only have bearing on thread safety?

这是一个简短的例子.多个线程将调用a();.

Here's a short example. Multiple threads will call a();.

public class A {
    public boolean a(File file) throws Exception {
        boolean t = true;
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            while(bin.read() > 0) {}
            return t;
        finally {
            try {
                if (in != null) in.close();
            } catch (IOException e) {}
            try {
                if (fin != null) fin.close();
            } catch (IOException e) {}
        }
    }
}

推荐答案

调用方法时,局部变量位于单个调用的堆栈中,因此在使用Multi-线程也一样,但是如果将相同的File作为参数传递,则可能会产生问题.

When you call a method then local variable resides in the stack of individual call, so you don't need to worry about the local variables in case of Multi-Threading as well, but it can create issue if same File is passed as argument.

阅读为什么局部变量在Java中是线程安全的

局部变量始终是线程安全的.但是请记住,局部变量指向的对象可能并非如此.如果对象是在方法内部实例化的,并且从未转义,则不会有问题.

Local variables are always thread safe. Keep in mind though, that the object a local variable points to, may not be so. If the object was instantiated inside the method, and never escapes, there will be no problem.

另一方面,指向某些共享对象的局部变量仍可能会引起问题.仅仅因为您将共享对象分配给本地引用,并不意味着该对象自动成为线程安全的.

On the other hand, a local variable pointing to some shared object, may still cause problems. Just because you assign a shared object to a local reference, does not mean that object automatically becomes thread safe.

请参见 JavaRanch-线程安全和局部变量.

如果局部变量是原始变量,则是的,它是线程安全的.如果局部变量是指向本地创建对象的引用,则可以,它应该是线程安全的(假定静态变量是线程安全的).

If the local variable is a primative variable, then yes, it is thread safe. If the local variable is a reference that is pointing to a locally created object, then yes, it should be thread safe (assuming the statics are thread safe).

如果局部变量是指向外部创建对象的引用,则且仅当可以以线程方式安全使用该对象时,该变量才是线程安全的.

If the local variable is a reference that is pointing to an externally created object, then it is thread safe, if and only if the object can be used safely in a threaded fashion.

这篇关于仅具有局部变量的实例方法的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:35