java 创建线程对象后调用实现runnable的Java类的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13370022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call the method of Java class which implements runnable after creating its thread object
提问by wali
I have a java class
我有一个java类
SomeClass implements Runnable
Which has a method display().
其中有一个方法 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?
现在如何使用线程实例调用 display() 方法?
回答by kosa
You will end up calling start()
on thread1
.
你最终会调用start()
上thread1
。
SomeClass
will override run()
method which in turn need to call display()
method.
SomeClass
将覆盖run()
方法,而方法又需要调用display()
方法。
This way when you call start()
, run method of SomeClass()
object will be invoked and display() method will be executed.
这样,当您调用时start()
,SomeClass()
将调用对象的run 方法并执行 display() 方法。
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.
如果您不使用 join(),正如 Andrew 评论的那样,结果可能会不一致。
回答by RNJ
If you want to call display from your new thread then it needs to be within you run method.
如果你想从你的新线程调用 display 那么它需要在你的 run 方法中。
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
如果你想从调用线程调用它然后创建一个新对象,将它传递给你的新线程,然后从你的下降线程调用 display
SomeClass sc = new SomeClass();
new Thread(sc).start();
sc.display()
回答by Tomasz Nurkiewicz
Simple delegation:
简单委托:
public class SomeClass implements Runnable {
@Override
public void run() {
display();
}
public void display() {
//...
}
}