Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Hilos con Java

No description
by

Dario Vallejos

on 26 September 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Hilos con Java

Hilos en JAVA
Hilos
Un hilo es un proceso ligero, nos permite la ejecución de tareas en forma paralela sin un costo asociado al cambio de proceso en los sistemas operativos
Hilos en java
Hay dos formas formas de implementar hilos en java
Extendiendo de la clase Thread
Implementando la interface runnable

public class Hilo extend Thread {

public void run(){
//lo que va hacerce en forma paralela
}

}
public class Hilo implements Runnable{
public void run(){
// ejecucion dentro del hilo
}
}
Inicialización de los hilos
La inicialización de los hilos se da mediante el método start() de la clase Thread, como tenemos dos formas de implementar hilos tambien tenemos dos formas de inicializarlos.
Cuando se extiende de Thread
Hilo h = new Hilo();
h.start();
Cuando se implementa runnable
Hilo h = new Hilo();
Thread t = new Thread(h);
t.start();
La clase Hilo extiende
de la clase Thread
La clase Hilo implementa
la interfase Runnable
La clase Thread
Los metodos mas importantes son:
Estados de los hilos
void start() -- para iniciar el hilo
static void sleep(long milliseg) -- para dormir el hilo
void join() -- para esperar a que termine un hilo para comenzar otro
boolean isAlive() -- pregunta si todavia no termino el hilo
static void yield() -- para pedirle al planificador tiempo de ejecucion
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

public static enum Thread.State
extends Enum<Thread.State>
A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
Sincronizacion
la sincronizacion en java significa cuidar la integridad de datos cuando hay mas de un hilo involucrado en el tratamiento
La palabra reservada synchronized :
synchronized public void funcion1(){
//...
}
public void mover(){
synchronized (this) {
indice++;
if (indice>= numeros.length) {
indice=0;
}
}
//...
}
productor consumidor
public class Productor extends Thread {
private Buffer buffer;
private final String letras="abcdefghijklmnopqrstuvxyz";
public Productor(Buffer buffer) {
this.buffer=buffer;
}
public void run() {
for(int i=0; i<10; i++){
char c=letras.charAt((int)(Math.random()*letras.length()));
buffer.poner(c);
System.out.println(i+" Productor: " +c);
try {
sleep(400);
} catch (InterruptedException e) { }
}
}
}
public class Consumidor extends Thread {
private Buffer buffer;
public Consumidor(Buffer buffer) {
this.buffer=buffer;
}
public void run(){
char valor;
for(int i=0; i<10; i++){
valor=buffer.recoger();
System.out.println(i+ " Consumidor: "+valor);
try{
sleep(100);
}catch (InterruptedException e) { }
}
}
}
public class Buffer {
private char contenido;
private boolean disponible=false;
public Buffer() {
}
public char recoger(){
if(disponible){
disponible=false;
return contenido;
}
return ('\t');
}
public void poner(char c){
contenido=c;
disponible=true;
}
}
productor
consumidor
buffer
public class ThreadApp2 {
public static void main(String[] args) {
Buffer b=new Buffer();
Productor p=new Productor(b);
Consumidor c=new Consumidor(b);
p.start();
c.start();
}
}
public class Buffer {
private char contenido;
private boolean disponible=false;
public Buffer() {
}

public synchronized char recoger(){
while(!disponible){
try{
wait();
}catch(InterruptedException ex){}
}
disponible=false;
notify();
return contenido;
}

public synchronized void poner(char valor){
while(disponible){
try{
wait();
}catch(InterruptedException ex){}
}
contenido=valor;
disponible=true;
notify();
}
}
usando wait() , notify() , sinchronized
http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class
sleep()
stack hilos
problema de concurrencia

solucion posible
import java.lang.*;

public class ThreadDemo implements Runnable {

public void run() {

Thread t = Thread.currentThread();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}

public static void main(String args[]) throws Exception {

Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
// waits for this thread to die
t.join();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
}
join ejemplo
http://www.avajava.com/tutorials/lessons/how-do-i-use-the-wait-and-notify-methods.html
http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
Full transcript