1. Práctica CNICE. En esta práctica vamos a poner un ejemplo de sincronización de threads.
Para ello vamos a desarrollar una clase contenedor (una especie de buffer) de una variable de tipo int. Este contenedor se
ha de asegurar en su implementación, que nunca puede haber dos threads escribiendo o borrando dicha variable a la vez.
Además, se ha de asegurar también que ningún thread pueda borrar el contenido de la variable hasta que otro thread haya
escrito, y que ningún thread pueda volver a escribir un valor nuevo hasta que otro thread lo haya borrado.
Escribir dos clases más que implementen al thread que escribe el valor en el contenedor y al thread que borra el valor en el
contenedor.
Por último, escribir una clase con el método main donde se creen y arranquen los dos threads.
Contenedor.java
public class Contenedor {
private int numero;
private boolean vacio = true;
public synchronized void borra(){
//MIENTRAS SE ESTÁ ESCRIBIENDO
while(vacio){//ESPERA
try{
wait();//Espera a que se termine el proceso de escritura para BORRAR
}catch(InterruptedException ex){}
}
//CUANDO FINALIZA EL PROCESO DE ESCRITURA BORRA EL BUFFER INFORMA QUE EL BUFFER YA ESTA VACIO
numero = -1; // -1 es vacío.
System.out.println("Buffer (Borrado) = [" + numero + "]");
vacio = true;
notify();
}
public synchronized void escribe(int valor){
//MIENTRAS SE ESTÁ BORRANDO
while(!vacio){//ESPERA
try{
wait();//Espera a que termine el proceso de borrado para ESCRIBIR
}catch(InterruptedException ex){}
}
//CUANDO SE VACIA EL BUFER ESCRIBE EL VALOR DEL NUMERO EN EL BUFER INFORMA QUE YA ESTA LLENO
numero = valor;
System.out.println("Buffer (escritura) = [" + numero + "]");
vacio = false;
notify();
}//Fin function
}
bitCoach::Juan Bautista Cascallar Lorenzo
2. ThreadBorrar.java
public class ThreadBorrar extends Thread {
private Contenedor bufer;
public ThreadBorrar(Contenedor bufer){
this.bufer = bufer;
}
public void run(){
for(int i=0; i < 10; i++){
bufer.borra();
try {
int t = (int) (Math.random() * 5000);
sleep(t);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
ThreadEscribir.java
public class ThreadEscribir extends Thread {
private Contenedor bufer;
public ThreadEscribir(Contenedor bufer){
this.bufer = bufer;
}
public void run(){
for(int i=0; i < 10; i++){
int num =(int) (Math.random() * 100);
bufer.escribe(num);
try {
int t = (int) (Math.random() * 5000);
sleep(t);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
bitCoach::Juan Bautista Cascallar Lorenzo
3. TestSincroThreads.java
public class TestSincroThreads {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Contenedor bufer = new Contenedor();
ThreadEscribir hilo_escritor = new ThreadEscribir(bufer);
ThreadBorrar hilo_borrador = new ThreadBorrar(bufer);
hilo_escritor.start();
hilo_borrador.start();
}
}
bitCoach::Juan Bautista Cascallar Lorenzo