【问题标题】:getting a variable from a different thread android java从不同的线程android java获取变量
【发布时间】:2015-11-30 15:13:47
【问题描述】:

我收到错误:android.os.networkonmainthreadexception。我发现,发生这种情况是因为我必须将 Internet 请求放在主线程以外的线程上。我已经搜索了将它放在单独线程上的方法,并使用了这个,因为我可以很好地理解它:

public void use() throws Exception
{
    int a;
    Thread thread = new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                //do something
        a=32;
        //do smthn else
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });

    thread.start();
int b= a;
}

我创建了一个新线程并将网络层放入其中。问题是,我无法从中获取变量。当我喜欢 int b= a;从代码中可以看出:变量(int a)是从内部类中访问的,需要声明为final(int b)。如何以简单的方式从变量中获取 int a 外部?

非常感谢所有帮助:) 谢谢。

【问题讨论】:

    标签: android multithreading android-studio runnable


    【解决方案1】:

    您可以使用LocalBroadcastManagerEventBus 将工作线程的结果报告回主/ui 线程。

    注意:这取决于上下文,但创建自己的“可运行”线程可能不是在 Android 上进行线程化的最佳方式。

    【讨论】:

      【解决方案2】:

      这里有个建议,让你的班级像这样实现Runnable

      public class MyClass implements Runnable
      {
          int a;
      
          public void use()
          {
              Thread thread = new Thread(this);
              thread.start();
          }
      
          public void run()
          {
              try
              {
                  //do something
              }
              catch (Exception e)
              {
                  e.printStackTrace();
              }
          }
      }
      

      这样,变量 'a' 在你的 Thread 和你的函数中都是可见的。在run() 的末尾,您可以调用一个设置b = a; 或类似的函数,在这种情况下,b 应该与顶部一起定义,但我不确定您要实现什么,所以您可以当法官。

      【讨论】:

        【解决方案3】:

        我在您的代码中发现了一个问题。那就是当你分配b = a时,可能线程还没有完成,所以变量b得到了错误的值。为了解决问题,我认为您可以在单独的线程中运行整个 use() 方法。

        如果您仍想只运行其中的某行,您可以尝试以下示例:

        class Wrapper {
            // Use wrapper for change the value of final primary variable
            int a;
        }
        
        public void use() {
            final Wrapper a = new Wrapper();
            Thread t = new Thread(new Runnable() {
        
                @Override
                public void run() {
                    a.a = 120;
                }
            });
            t.start();
        
            // Block current thread until t finish
            // So make sure b get the right value
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int b = a.a;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多