how to share a variable between two threads
Posted
by prmatta
on Stack Overflow
See other posts from Stack Overflow
or by prmatta
Published on 2010-03-17T22:35:01Z
Indexed on
2010/03/17
22:41 UTC
Read the original article
Hit count: 240
I just inherited some code, two threads within this code need to perform a system task. One thread should do the system task before the other thread. They should not be performing the system task together. The two threads do not have references to each other.
Now, I know I can use some sort of a semaphore to achieve this. But my question is what is the right way to get both threads to access this semaphore.
I could create a static variable/method a new class :
public class SharedSemaphore
{
private static Semaphore s = new Semaphore (1, true);
public static void performSystemTask () {
s.acquire();
}
public static void donePerformingSystemTask() {
s.release();
}
}
This would work (right?) but this doesn't seem like the right thing to do. Because, the threads now have access to a semaphore, without ever having a reference to it. This sort of thing doesn't seem like a good programming practice. Am I wrong?
© Stack Overflow or respective owner