Arvind
Arvind

Reputation: 6474

How to update the value of a variable being used in a thread in java

In a java program, I am running same function across multiple threads. What I want to do is this--

  1. 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)
  2. 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?
  3. 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".
  4. Terminate one (specific) running thread. Eg I wish to terminate Thread1 (from the 2 running threads above).

Upvotes: 0

Views: 664

Answers (1)

shazin
shazin

Reputation: 21883

Answers for

  1. There are couple of Ways to do this. You can either; A Util class named ThreadUtil and inside have a static Set<Thread>. You can add the threads you create to set and remove whenever the thread finishes executing. Or you can extend from ThreadPoolExecutor and override methods beforeExecute, afterExecute methods 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.
  2. This is possible by using ThreadLocal class. See this post on how to use ThreadLocal
  3. Possible with ThreadLocal
  4. You can make use of a Flag (boolean stop) in the thread to do this, and a method to set this flag to true

Upvotes: 1

Related Questions