如何通过线程访问Runnable对象? [英] How to access a Runnable object by Thread?
问题描述
可能重复: need-help-returning-object-in-线程运行方法
Hello。我有一个类实现runnable,我有一个List,存储Threads实例化与该类的不同对象。给定线程对象运行它们时如何访问底层对象的属性?下面是一个例子:
Hello. I have a class implementing runnable and I have a List, storing Threads instantiated with different objects of that class. How can I access properties of underlying objects given the thread object running them? Here is an example:
public class SO {
public static class TestRunnable implements Runnable {
public String foo = "hello";
public void run() {
foo = "world";
}
}
public static void main(String[] args) {
Thread t = new Thread(new TestRunnable());
t.start();
//How can I get the value of `foo` here?
}
}
推荐答案
I没有看到任何方法在 java.lang.Thread
docs。
I don't see any way to do it in the java.lang.Thread
docs.
我最好的答案是,应该使用 List< Runnable>
而不是(或除了) List< Thread>
。或者,您可能需要某种地图 a>结构,以便您可以从Thread访问Runnable。 (例如, java.util.HashMap< java.lang.Thread,java.lang.Runnable>
)
My best answer, then, is that you probably should be using List<Runnable>
instead of (or in addition to) List<Thread>
. Or perhaps you want some sort of map structure so that you can access the Runnable from the Thread. (For example, java.util.HashMap<java.lang.Thread, java.lang.Runnable>
)
这篇关于如何通过线程访问Runnable对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!