[Solved] Is there a way to obtain an instance of a running thread?

I have an anonymous Thread object:


new Thread(new Runnable() {
	@Override
	public void run() {
		try {
			Thread.sleep(2000);
		}
		catch (InterruptedException e) {
		}
	}
}).start();

This anonymous thread is inside a loop, and will run when the conditions are met in the loop.

I wanted to know if I can obtain an instance of the running anonymous Thread object without creating a class member of type Thread and make it reference to the anonymous Thread object, so that the application won’t start the Thread object too many times in the loop.

I was thinking of using [icode]Thread.currentThread()[/icode] static method to get the instance, but the more I think of it, the more difficult it is to come up with a solution. Hm…

Assigning the thread reference to a field or variable doesn’t change anything.

On second thought, creating a new field in a class object and then passing the thread reference to that is the only way to obtain the reference outside of the anonymous Thread object that is running in the background (with its state being Thread.State.RUNNING).

I tried to get the reference of an anonymous Thread while it is running and outside of the anonymous Thread class scope, but I never gotten anywhere with it. Deciding to give up, this is marked as solved.

It is an anonymous object for a reason, you create and instantiate a class without having to give it a name.

Ofc at the top of your class you could have an array of threads, then when the thread starts you can do something like:



new Thread(new Runnable() {
   @Override
   public void run() {
   // Add the thread to a list
    threads.add(this);

      try {
         Thread.sleep(2000);
      }
      catch (InterruptedException e) {
      }
   }
}).start();


However that sucks, personally if you need fine control over threads you could create your own class that implements runnable and holds its own thread, then you can use a method to get the instance of the thread within that object.

Just what I can think of, I am not any good with threads at all. In fact I have a bad relationship with them hehe.

[icode]threads[/icode] has better be a SynchronizedList. (I don’t get the grammar of this sentence, but wut ya gonna do)

Like I said I am terrible with threads lol, I tend to avoid them. That was just my suggestions, assuming the op would know that, especially if they are even touching threads.

I actually never thought about it, when you got threads accessing the same things, all shit goes pear shaped unless you are prepared.