这个代码中的StringBuilder变量线程是否安全?

Joh*_*ohn 2 java stringbuilder thread-safety

考虑下面的struts Action类,我StringBuilder在execute方法中使用了一个变量.我的问题:变量sb线程是否安全?

public DemoAction extends Action
{
    ......

    public ActionForward execute(.....)
    {
       StringBuilder sb = new StringBuilder();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果在execute()之外声明了相同的变量sb,该怎么办?请记住,WebContainer中只有一个DemoAction对象.

Kon*_*lph 15

局部变量是线程安全的,只要没有其他线程以某种方式获得对同一字符串构建器实例的引用,它就是线程安全的.