Call the method of Java class which implements run

2019-07-23 06:49发布

问题:

I have a java class

SomeClass implements Runnable

Which has a method display().

When I create a thread of this class

Thread thread1 = new Thread(new SomeClass());

Now how I can call the display() method using the thread instance?

回答1:

You will end up calling start() on thread1.

SomeClass will override run() method which in turn need to call display() method.

This way when you call start(), run method of SomeClass() object will be invoked and display() method will be executed.

Example:

public class SomeClass implements Runnable {
    private List yourArrayList;
    public void run() {
        display();
    }

    public void display() {
        //Your display method implementation.
    }
   public List methodToGetArrayList()
   {
    return  yourArrayList;
   }
}

Update:

SomeClass sc = new SomeClass()
Thread thread1 = new Thread(sc);
thread1.join();
sc.methodToGetArrayList();

NOTE: Example is to illustrate the concept, there may be syntax errors.

If you don't use join(), as Andrew commented, there may be inconsitence in results.



回答2:

If you want to call display from your new thread then it needs to be within you run method.

If you want to call it from the calling thread then create a new object, pass this into your new thread and then call display from your falling thread

SomeClass sc = new SomeClass();
new Thread(sc).start();
sc.display()


回答3:

Simple delegation:

public class SomeClass implements Runnable {

    @Override
    public void run() {
        display();
    }

    public void display() {
        //...
    }

}