views:

87

answers:

2

When an object is instantiated in Java, is it bound to the thread that instantiated in? Because when I anonymously implement an interface in one thread, and pass it to another thread to be run, all of its methods are run in the original thread. If they are bound to their creation thread, is there anyway to create an object that will run in whatever thread calls it?

+1  A: 

The object is not bound to the thread it was created on... the only way you'll have the methods being executed on the main thread is if you call them on the main thread.

It's relatively easy to see which thread is calling the method... simply make a dummy function:

public threadDetect(string which)
{
    System.out.println("Executed from " + which + " thread.");
}

In the main thread you call:

threadDetect("main");

From the child thread you call:

threadDetect("child");

I'm not sure if the OP is using a similar way to detect which thread is executing the method, but this is one way to do it.

Lirik
+2  A: 

If thread A creates an object:

MyClass.staticMember = new Runnable() {...};

and thread B invokes a method on that object:

MyClass.staticMember.run();

then the run() method will execute in thread B.

Thread A will simply keep running whatever code it happens to be running at the time.

Martin
Well it definitely is running the object's methods in the original thread. The error it gave me was pretty specific. If it is any help, this all on the Android, rather than a standard Java VM.
Veered
In the case I posted above, **run()** will always, without exception, execute in thread B. Post more code and we might be able to help. Mark's explanation of drawing APIs sounds spot on.
Martin