Você está na página 1de 2

class LectoresEscritores extends MyObject{ private int nEscritor;; private int nLector; private boolean ocupado; private ConditionVariable

escritor= null; private ConditionVariable lector = null; private int[] elementos; public LectoresEscritores(){ nEscritor=0; nLector=0; ocupado=false; escritor=new ConditionVariable(); lector=new ConditionVariable(); elementos=new int[10]; } public synchronized void obtenerLector() { if(nEscritor>0){ wait(lector); } nLector++; notify(lector); } public synchronized void liberarLector() { nLector--; if(nLector == 0) {notify(escritor);} } public synchronized void obtenerEscritor() { nEscritor++; while(nLector > 0 ocupado) {wait(escritor);} ocupado=true; } public synchronized void leer(int k){ System.out.println("***Lector " +k+" leyendo...*"); } public synchronized void escribir(int p){ System.out.println("-----Escritor " +p+" Escribiendo...-"); } public synchronized void liberarEscritor() { ocupado=false; nEscritor--; if(nEscritor>0){wait(escritor); } notify(lector); } }

/////procesos class Proceso1 extends Thread{ private LectoresEscritores l; public Proceso1(LectoresEscritores le) { this.l =le; } public void run(){

for(int i=1;i<=20;i++) { l.obtenerLector(); l.leer(i); l.liberarLector(); try { sleep( (int)Math.random()*3000 ); } catch(InterruptedException e) { System.out.println("Error "+e.toString()); } } } } class Proceso2 extends Thread{ private LectoresEscritores l; public Proceso2(LectoresEscritores le) { this.l =le; } public void run(){ for(int i=1;i<=20;i++) { l.obtenerEscritor(); l.escribir(i); l.liberarEscritor(); try { sleep( (int)Math.random()*3000 ); } catch(InterruptedException e) { System.out.println("Error "+e.toString()); } } } } class Principal{ public static void main(String[] args){ LectoresEscritores lec= new LectoresEscritores(); Proceso1 p1 = new Proceso1(lec); Proceso2 p2 = new Proceso2(lec); p2.start(); //escritores p1.start(); //lectores } }

Você também pode gostar