In a java program, I am running same function across multiple threads.
What I want to do is this–
- Identify specific running threads– eg if there are 2 running threads how can I access one of those threads from an external function? (The external function is part of the same java app that has the threads)
- Suppose there is a variable named “x” that is being used across both the threads above. Can I store and retrieve separate values for “x” in thread1 and thread2? Is this the default behaviour for any variable used in a thread?
- Access/update values of variables in a specific thread– eg I wish to update value of “x” as it is being used in “thread 1”.
- Terminate one (specific) running thread. Eg I wish to terminate Thread1 (from the 2 running threads above).
Answers for
A Util class named
ThreadUtiland inside have astatic Set<Thread>. You can add the threads you create to set and remove whenever the thread finishes executing.Or you can extend from
ThreadPoolExecutorand override methodsbeforeExecute,afterExecutemethods to do the same thing above. The you can use the set to get the running threads. You can use a map if you want to store and retrieve by name.ThreadLocalclass. See this post on how to useThreadLocalThreadLocalboolean stop) in the thread to do this, and a method to set this flag totrue