I have a program that holds many threads, lets put as an example six threads. Five of them should be able to use concurrently a given resource but the last thread shouldn’t if a given condition occurs and should wait until that condition is over.
In my understanding a ReentrantLock can’t be used because it can only be held by one thread at a time. In the other hand a Semaphore can be held by many threads at a time but I can’t find a way to attach the condition to aquire method.
Can This high level objects do the trick or I will have to implement this functionality using notify and wait directly?
Eg.
class A{
getResource{ ... }
}
//This Runable could be spawn many times at the same time
class B implements Runnable{
run {
setConditionToTrue
getResource
...
getResource
...
getResource
setConditionToFalse
}
}
//This will be working forever but only one Thread
class C implements Runnable{
run{
loop{
if(Condition == true) wait
getResource
}
}
}
Thanks in advance pals
I am restating your problem here: You want your B threads to access the shared resource concurrently, but your C thread should wait for some condition to occur before using the resource.
If I understand your question correctly, You can use
ReentrantLockto solve your problem.Introduce a new function called
getAccess()and make the C thread call this function to get the shared resource. Introduce two more functions to allow and stop the access to shared resource.