Middle+
Kas teil on kogemusi semaforidega Android rakenduste arendamisel?
sobes.tech AI
Vastus AI-lt
Yes, I have experience. Semaphores are used to control access to limited resources in a multithreaded environment. In Android development, this is useful for managing parallel access to shared data, for example, when working with databases or network requests from different threads.
I use the Semaphore class from the java.util.concurrent package.
Main methods:
acquire(): acquires permission. If none are available, the thread is blocked.release(): releases the permission, increasing the number of available permits.
Example of usage to limit parallel access to a resource:
import java.util.concurrent.Semaphore;
// Declare a semaphore with 2 permits
private final Semaphore resourceSemaphore = new Semaphore(2);
public void accessResource(int threadId) {
try {
// acquire permission, block if limit is reached
resourceSemaphore.acquire();
System.out.println("Thread " + threadId + " has accessed the resource.");
// simulate work with the resource
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// release permission
resourceSemaphore.release();
System.out.println("Thread " + threadId + " released the resource.");
}
}
Semaphores allow efficient management of resource pools and prevent race conditions. It is important to carefully plan the number of permits and correctly handle their acquisition and release to avoid deadlocks.