INFORMATICA III ESCUELA DE INGENIERIA ELECTRONICA DEPARTAMENTO DE SISTEMAS E INFORMATICA
LA CLASE THREAD –CONSTRUCTORES –METODOS –METODOS SYNCHRONIZED ANULADOS –SENTENCIAS SYNCHRONIZED GRUPOS DE THREADS –CONSTRUCTORES –METODOS INTERFACE RUNNABLE EXCEPCIONES
Ing. E.D'AgostinoINFORMATICA III Constructores má usados de Thread public Thread ( String threadName) construye un thread cuyo nombre es threadName public Thread () construye un thread cuyo nombre es Thread concatenado con un dígito (Thread1, Thread2) public Thread(Runnable target) Target es el objeto cuyo método run se va a ejecutar
Ing. E.D'AgostinoINFORMATICA III La clase Thread Métodos más importantes: public synchronized void start() Causa que este thread comience a ejecutarse; la MVJ llama al método run de este thread. public void run() activa el thread public final synchronized void join(long millis) throws InterruptedException espera por la terminación
Ing. E.D'AgostinoINFORMATICA III public void interrupt() sale de un wait, sleep o join public boolean isInterrupted() determina si un hilo ha sido interrumpido public static void yield() cede el paso La clase Thread
Ing. E.D'AgostinoINFORMATICA III public final void stop() Fuerza que el hilo detenga su ejecución public final void suspend() cuando se invoca pasa al estado suspendido public final void resume() abandona el estado suspendido public String toString() Retorna un String que representa al hilo La clase Thread
Ing. E.D'AgostinoINFORMATICA III Métodos estáticos más interesantes: public static Thread currentThread() public static void sleep(long millis) throws InterruptedException La clase Thread
Ing. E.D'AgostinoINFORMATICA III Métodos de la clase Object que controlan la suspensión del Thread actual: wait() (equivale a 0 milisegundos) wait (milisegundos) notify ()notifyAll() La clase Thread
Ing. E.D'AgostinoINFORMATICA III Wait y notify Sirven para comunicar los threads entre sí synchronized void cuandoCondicion ( ) { while ( ! condicion ) wait ( ); ….hacer lo que sea necesario cuando la condicion sea cierta }
Ing. E.D'AgostinoINFORMATICA III synchronized void cambiaCondicion ( ) { ….cambiar algún valor usado en condición notify ( ) ; // notifyAll ( ) } Wait y notify
Ing. E.D'AgostinoINFORMATICA III Para que el contenido del objeto sea estable todo debe ocurrir en método synchronized. Cuando se suspende el thread libera en forma atómica el bloqueo del objeto. La prueba de la condición debe estar siempre en un bucle. Wait y notify
Ing. E.D'AgostinoINFORMATICA III public final void wait (long timeout) throws InterruptedException public final void wait (long timeout, int nanos) throws InterruptedException public final void wait () throws InterruptedException Wait
Ing. E.D'AgostinoINFORMATICA III Notify public final notify ( ) public final notifyAll ( )
Ing. E.D'AgostinoINFORMATICA III PÉRDIDA DEL ESTADO DE EJECUCIÓN Un thread deja su estado de ejecución por una de las siguientes causas: El método sleep se invoca. El thread llama al método wait y espera que una determinada condición se satisfaga. El thread está bloqueado por una I/O. El método suspend se invoca.
Ing. E.D'AgostinoINFORMATICA III Métodos synchonized anulados Si una clase extendida anula un método synchronized, el nuevo método puede o no ser synchronized. El método de la superclase continúa siendo synchronized.
Ing. E.D'AgostinoINFORMATICA III Sentencias synchronized Permite ejecutar código sincronizado sin invocar un método sincronizado sentencia bloqueo
Ing. E.D'AgostinoINFORMATICA III Forma general: synchronized (expresión) sentencia Sentencias synchronized Objeto a bloquear
Ing. E.D'AgostinoINFORMATICA III public static void abs (int [] values) { synchronized (values) { for (int i = 0; i< values; i++) { if (values [i] < 0) values [i] = -values[i]; } Sentencias synchronized
Ing. E.D'AgostinoINFORMATICA III public class ThreadGroup extends Object Un thread group representa un conjunto de hilos. Un thread group puede incluir también otros thread groups. Grupos de hilos
Ing. E.D'AgostinoINFORMATICA III Tiene dos constructores: public ThreadGroup (String cadenanombre) construye un ThreadGroup cuyo nombre es cadenanombre public ThreadGroup ( ThreadGroup padre, String cadenanombre) construye un ThreadGroup hijo de padre, llamado cadenanombre Grupos de hilos
Ing. E.D'AgostinoINFORMATICA III La clase Thread tiene tres constructores que permiten crear un Thread y asociarlo a un grupo: –public Thread (ThreadGrroup threadGroup, String nombre) –public Thread (ThreadGrroup threadGroup, Runnable objetoEjecutable) –public Thread (ThreadGrroup threadGroup, Runnable objetoEjecutable, String cadena) Grupos de hilos
Ing. E.D'AgostinoINFORMATICA III Métodos principales de ThreadGroup public int activeCount(); Retorna el numero de hilos activos public int activeGroupCount(); Retorna el numero de grupos activos
Ing. E.D'AgostinoINFORMATICA III public final void checkAccess(); Determina si el thread actual tiene permiso para modificar el thread group. Si no tiene permiso lanza una excepción. public final void destroy() ; Destruye este thread group y todos sus subgrupos Métodos de ThreadGroup
Ing. E.D'AgostinoINFORMATICA III public int enumerate(Thread list[]) Copia en el arreglo cada thread activo de este thread public int enumerate(Thread list[], boolean recurse) Igual al anterior. Si el argumento booleano es true copia las referencias a los thread que pertenecen a los subgrupos que forman parte del thread group. Si el arreglo es demasiado chico, los ignora sin avisar nada. Métodos de ThreadGroup
Ing. E.D'AgostinoINFORMATICA III public final ThreadGroup getParent(); Retorna el padre del ThreadGroup public final boolean isDaemon() Testea si este thread group es daemon.Un daemon thread group se destruye automaticamente cuando el ultimo thread es parado o su ultimo thread group se destruye public void list(); Imprime información sobre el grupo en la salida estandar.Es útil para public final boolean parentOf(ThreadGroup g); Testea si el thread group es el thread group del argumento o uno de sus ancestros Métodos de ThreadGroup
Ing. E.D'AgostinoINFORMATICA III public interface Runnable La interface Runnable debería ser implementada por cualquier clase cuyas instancias vayan a ser ejecutadas por un thread. La clase debe definir un metodo llamado run sin argumentos. Interface Runnable
Ing. E.D'AgostinoINFORMATICA III Excepciones que pueden sel lanzadas por métodos de threads SecurityException (checkAccess) IlegalArgumentException (setPriority) IlegalThreadStateException (suspend/resume) InterruptedException (otro thread quiere interrumpir el actual)
Ing. E.D'AgostinoINFORMATICA III BIBLIOGRAFÍA Como programar en java Deitel y Deitel. Pearson Educación Java. Fundamentos de Programación Judy Bishop. Addison-Wesley