Java desde la versión 1.5 contiene la clase java.util.concurrent.Semaphore para el uso de Semáforos (un semáforo binario es un indicador de condición que registra si un recurso está disponible) o no.
Podéis encontrar numerosa documentación sobre el problema que soluciona, como en http://casidiablo.net/semaforos-java/
Yo me quedo con este ejemplo Copy&Paste:
| import java.util.concurrent.locks.*;
import java.util.concurrent.Semaphore; public class SemaphoreExample { int i = 0; public static void main (String[] args) { final SemaphoreExample example = new SemaphoreExample(); final Semaphore semaphore = new Semaphore (1); final Runnable r = new Runnable () { public void run () { while (true) { try { semaphore.acquire(); //Sección crítica a proteger example.printSomething (); Thread.sleep (1000); semaphore.release(); } catch (Exception ex) { System.out.println (" — Interrupted…"); ex.printStackTrace (); } } } }; new Thread (r).start (); new Thread (r).start (); new Thread (r).start (); } public void printSomething (){ i++; System.out.println (" — current value of the i :"+ i); } } |

Deja un comentario