2. Hilos en Java
Uso de extends Thread
public class MiHilo extends Thread{
public void run (){
while (true){
System.out.println(Math.random());
try{ Thread.sleep(2000);}
catch(Exception e){ System.out.println("Error");
}
}
}
}
3. Hilos en Java
Uso de implements Reunnable
public class MiHilo implements Runnable{
public void run (){
@Override
while (true){
System.out.println(Math.random());
try{ Thread.sleep(2000); }
catch(Exception e){System.out.println("Error");
}
}
}
}
4. Hilos en Java
Ejecución
public class PrincipalMiHiloRunnable {
public static void main (String args[]){
MiHilo mihilo = new MiHilo();
mihilo.start();
}
}
5. Semáforos en Java
public class Semaphore {
private boolean signal = false;
public Semaphore(){}
public synchronized void take() {
this.signal = true;
this.notify();
}
public synchronized void release() throws InterruptedException{
while(!this.signal) wait(); // this.signal == false;
this.signal = false;
}
}
6. Semáforos en Java
public class SendingThread extends Thread {
Semaphore semaphore = null;
public SendingThread(Semaphore semaphore){this.semaphore = semaphore; }
public void run(){
while(true){
//critical section
System.out.println("Enviando");
try{ Thread.sleep(2000);}
catch(InterruptedException e) { e.printStackTrace();}
//send signal
this.semaphore.take();}
}
}
}
7. Semáforos en Java
public class ReceivingThread extends Thread {
Semaphore semaphore = null;
public ReceivingThread(Semaphore semaphore){this.semaphore = semaphore;}
public void run(){
while(true){
//Receive signal, then do something...
try{ this.semaphore.release();}
catch(InterruptedException e){e.printStackTrace();}
//Critical Section
System.out.println("Recibiendo");
try{ Thread.sleep(2000);}
catch(InterruptedException e) {e.printStackTrace();}
}
}
}
8. Semáforos en Java
public class MiHiloPrincipal {
public static void main (String args []){
Semaphore semaphore = null;
SendingThread sending = new SendingThread(semaphore);
ReceivingThread receiving = new
sending.start();
receiving.start();
}
}