为什么不会将对象从参数传递到新线程内部

时间:2014-01-29 11:23:39

标签: java multithreading

在下面的代码中,当我致电doSomethingCool(x);时,我遇到的问题是我无法获得myco.name的值;当它在线的一边。如何将其传递到线程内?

MyCustomObj x = new MyCustomObj();
x.name = "test";


doSomethingCool(x); 


    protected void doSomethingCool(final MyCustomObj myco) {
        Thread t = new Thread() {

            public void run() {

                  //Myco is null  why?
                  String sName = myco.name; ////Why wont the object Myco pass through to here?

            }
        };

        t.start();      
    }

4 个答案:

答案 0 :(得分:1)

你已经正确地写了。这是调试器问题。

我在Eclipse / Android插件中经常看到这种无意义的调试。有时重启IDE(eclipse)会有所帮助。有时我只能重启模拟器。一旦我不得不重新启动计算机(它在Linux中!)。

此外,将try / catches放入并将断点放入捕获中。

答案 1 :(得分:0)

您可能需要将MyCustomObj.name标记为volatile,以保证所有线程都看到相同的值。

例如:

public class MyCustomObj {
    public volatile String name;
}

答案 2 :(得分:0)

您将拥有该String的值。请参阅下面的代码 -

public class Exct
{
    Me m=new Me();
    String s;
    public static class Me
    {
        public String ht()
        {
            return "me";
        }
    }

    public static void main(String ... args)
    {
        Exct c=new Exct();
        try
        {
            System.out.println(c.call(c.m)+" in main");
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    public String call(final Me m) throws Exception
    {

        Thread t=new Thread()
        {
            public void run()
            {
                s=m.ht();
                System.out.println(s+" in run");

            }
        };
        t.start();
        //System.out.println(s+" in run return ");
        //t.sleep(1);
        return s;
    }
}

这里的输出是 -

在main中为null 我在跑步

因为当t.start()执行时会搜索run方法,但是由于java的多线程功能,同时执行return语句并返回null值。

现在如果你做任何可以等待线程直到run方法执行的东西,那么返回的值将是准确的。我们可以通过打开那个null但是在一段时间之后返回执行的打印行来做到这一点,或者我们可以使该线程睡眠甚至1秒将完成剩下的并且输出将是 -

我跑了 我在主要

现在我没有任何其他解释,我会在找到任何其他好的解决方案时更新它。

答案 3 :(得分:-1)

通常,如果我们需要将参数传递给线程,我们可以使用下面提到的两种方法之一:

  1. 像这样创建自定义Runnable:

    public class MyRunnable implements Runnable{
    
    private MyCustomObj obj;
    
    public MyRunnable( MyCustomObj obj) {
    
      this.obj = obj;
    
    }
    
    public void run() {
    
      System.out.println("Name:" + obj.name );
    
    }
    

    }

  2. 然后

    MyCustomObj x = new MyCustomObj();
    x.name = "test";
    Thread t = new Thread(new MyRunnable(x));
    t.start();
    

    2.创建如下的自定义线程:

    public class MyThread extends Thread{
    
    private MyCustomObj obj;
    
    public MyThread( MyCustomObj obj) {
    
    this.obj = obj;
    
    }
    
    public void run() {
    
    System.out.println("Name:" + obj.name );
    
    }
    }
    

    然后

     MyThread t = new MyThread(x);
     t.start();
    

    希望这有助于你