Search code examples
javamultithreadingheap-memorystack-memoryanonymous-class

Basic Java Multi-Threading Question


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?


Solution

  • 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.