SlideShare una empresa de Scribd logo
1 de 8
Descargar para leer sin conexión
Hilos y Semáforos en Java
Implementación
Juan C. García-Ojeda
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");
}
}
}
}
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");
}
}
}
}
Hilos en Java
Ejecución
public class PrincipalMiHiloRunnable {
public static void main (String args[]){
MiHilo mihilo = new MiHilo();
mihilo.start();
}
}
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;
}
}
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();}
}
}
}
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();}
}
}
}
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();
}
}

Más contenido relacionado

Destacado (15)

Diapositivas de practica
Diapositivas de practicaDiapositivas de practica
Diapositivas de practica
 
Audio cassete taller #7
Audio cassete taller #7Audio cassete taller #7
Audio cassete taller #7
 
Ingenieria de sotware
Ingenieria de sotwareIngenieria de sotware
Ingenieria de sotware
 
Filósofos
FilósofosFilósofos
Filósofos
 
Problema de los Filosofos
Problema de los FilosofosProblema de los Filosofos
Problema de los Filosofos
 
Sistemas control
Sistemas controlSistemas control
Sistemas control
 
Sistema operativos semáforos
Sistema operativos  semáforosSistema operativos  semáforos
Sistema operativos semáforos
 
Hilos en java
Hilos en javaHilos en java
Hilos en java
 
Semáforos, monitores y paso de mensajes
Semáforos, monitores y paso de mensajesSemáforos, monitores y paso de mensajes
Semáforos, monitores y paso de mensajes
 
Monitores
MonitoresMonitores
Monitores
 
El semáforo
El semáforoEl semáforo
El semáforo
 
Semaforos
SemaforosSemaforos
Semaforos
 
Capitulo7 semaforos
Capitulo7 semaforosCapitulo7 semaforos
Capitulo7 semaforos
 
Semáforos
SemáforosSemáforos
Semáforos
 
Paginas de matematicas
Paginas de matematicasPaginas de matematicas
Paginas de matematicas
 

Similar a Hilos semaforos

Similar a Hilos semaforos (20)

Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Java 104
Java 104Java 104
Java 104
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
About java
About javaAbout java
About java
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
Java Hello World Program
Java Hello World ProgramJava Hello World Program
Java Hello World Program
 
Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Turbinando o compilador do Java 8
Turbinando o compilador do Java 8
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Loop
LoopLoop
Loop
 
Thread
ThreadThread
Thread
 
Class 5 2ciclo
Class 5 2cicloClass 5 2ciclo
Class 5 2ciclo
 
Language fundamentals ocjp
Language fundamentals ocjpLanguage fundamentals ocjp
Language fundamentals ocjp
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Introduction to-java
Introduction to-javaIntroduction to-java
Introduction to-java
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphism
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 

Más de Juan Carlos García Ojeda (13)

Enlace esteganografia
Enlace esteganografiaEnlace esteganografia
Enlace esteganografia
 
Discrecional Aprendizaje de Máquin Cádula Impar
Discrecional Aprendizaje de Máquin Cádula ImparDiscrecional Aprendizaje de Máquin Cádula Impar
Discrecional Aprendizaje de Máquin Cádula Impar
 
Discrecional Aprendizaje de Máquinas Cedula Par
Discrecional Aprendizaje de Máquinas Cedula ParDiscrecional Aprendizaje de Máquinas Cedula Par
Discrecional Aprendizaje de Máquinas Cedula Par
 
Exercicio k means
Exercicio k meansExercicio k means
Exercicio k means
 
Segundo parcialsimulacro
Segundo parcialsimulacroSegundo parcialsimulacro
Segundo parcialsimulacro
 
Taller Aprendizaje M´squina
Taller Aprendizaje M´squinaTaller Aprendizaje M´squina
Taller Aprendizaje M´squina
 
Solucion bano unisex
Solucion bano unisexSolucion bano unisex
Solucion bano unisex
 
Ejercicio sincronización
Ejercicio sincronizaciónEjercicio sincronización
Ejercicio sincronización
 
Sistemas Multiagente
Sistemas MultiagenteSistemas Multiagente
Sistemas Multiagente
 
Ejercicio ID3 Datos Numericos
Ejercicio ID3 Datos NumericosEjercicio ID3 Datos Numericos
Ejercicio ID3 Datos Numericos
 
Mineríade datos
Mineríade datosMineríade datos
Mineríade datos
 
Planning Evacuation Routes with the P-graph Framework
Planning Evacuation Routes with the P-graph FrameworkPlanning Evacuation Routes with the P-graph Framework
Planning Evacuation Routes with the P-graph Framework
 
1. introducción a Agentes
1. introducción a Agentes1. introducción a Agentes
1. introducción a Agentes
 

Último

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfSuman Jyoti
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 

Último (20)

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 

Hilos semaforos

  • 1. Hilos y Semáforos en Java Implementación Juan C. García-Ojeda
  • 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(); } }