how to share a variable between two threads
- by prmatta
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?