Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Runnable object by Thread?

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?     } } 
like image 620
Fluffy Avatar asked Feb 20 '10 00:02

Fluffy


People also ask

What is a runnable object what is a thread?

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.

Does thread implement 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.


1 Answers

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>)

like image 192
Platinum Azure Avatar answered Oct 20 '22 20:10

Platinum Azure