class ContadorCompartido |
public class ContadorCompartido { private
int n = 0; public int getN(String id) { return n; } public void setN(String id, int n) { this.n = n; System.err.println(id + ": " + n); } } |
class IncrementadorLento |
import
java.util.concurrent.Semaphore; public class
IncrementadorLento extends Thread { private final String id; private final ContadorCompartido cc; private static Semaphore semaforo = new
Semaphore(1); public IncrementadorLento(String id,
ContadorCompartido cc) { this.id = id; this.cc = cc; } @Override public void run() { try { semaforo.acquire(); } catch (InterruptedException e) { System.err.println(id + ":
" + e); } try { int valor = cc.getN(id); valor++; sleep(1000); cc.setN(id, valor); } catch (InterruptedException e) { System.err.println(id + ":
" + e); } finally {
semaforo.release(); } } } |
Temas relacionados
Semáforo [semaphore] (concepto)