Call the method of Java class which implements runnable after creating its thread object

旧巷老猫 提交于 2020-01-24 12:17:35

问题


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() {
        //...
    }

}


来源:https://stackoverflow.com/questions/13370022/call-the-method-of-java-class-which-implements-runnable-after-creating-its-threa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!