Possible duplicate: need-help-returning-object-in-thread-run-method
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? } }
Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement Runnable. There is no need of subclassing a Thread when a task can be done by overriding only run() method of Runnable.
The Thread class itself implements Runnable with an empty implementation of run() method. For creating a new thread, create an instance of the class that implements Runnable interface and then pass that instance to Thread(Runnable target) constructor.
I don't see any way to do it in the java.lang.Thread
docs.
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>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With