线程是否共享方法的局部变量

线程是否共享方法的局部变量

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

问题描述

此问题是此问题的扩展问题.

如果在该问题中,AbcRunnable将具有一个成员变量作为类,该成员变量仅具有从Runnable进行调用的方法,该怎么办?例如

What if in that question AbcRunnable would have a member variable as a class which only has methods which are getting called from Runnable. E.g.

public class AbcRunnable implements Runnable
{
     private final AbcSupplier supplier;

     public void run() {

        List<Message> messages = supplier.get();
     }
}

public class AbcSupplier implements Supplier<List<Message>> {

     public List<Message> get() {
         List<Message> list = new ArrayList<>();
         /*
          Some operations on list
         */
         return list
     }
}

因此,在这种情况下,如果2个线程共享AbcSupplier的对象,因为我们仅创建它的一个实例.然后,他们还会在其中共享局部变量列表吗?还是不会?

So, in this case, if 2 threads are sharing the object of AbcSupplier because we are creating only one instance of it. Then, will they also share the local variable list in there? Or they won't be?

我尝试自己运行它.在我看来,他们正在得到分享,但不是100%肯定.

I tried running it by myself. To me, it looked like, they are getting shared but not 100% sure.

推荐答案

否.运行AbcRunnable.run()的两个线程不会共享AbcSupplier.get()返回的列表的相同实例.这是因为get()每次运行时都会创建一个ArrayList实例.

No. Two threads running AbcRunnable.run() won't share the same instance of the list returned by AbcSupplier.get(). This is because get() creates an ArrayList instance every time it runs.

这是一个导致线程共享同一列表的版本:

Here's a version that would cause threads to share the same list:

public class AbcSupplier implements Supplier<List<Message>> {

     List<Message> list = new ArrayList<>();
     public AbcSupplier() {
         ......
         Some operations on list
         ......
     }

     public List<Message> get() {
         return list;
     }
}

在这种情况下,相同的AbcSupplier实例将返回相同的List实例.

In this case, the same AbcSupplier instance would return the same List instance.

这篇关于线程是否共享方法的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:35