Diseño Y Aplicaciones de Sistemas Distribuidos Programación concurrente en Java Joan Vila DISCA / UPV Departament d Informàtica de Sistemes i Computadors Universitat Politècnica de València
Threads en Java Indice La clase Thread El interfaz Runnable Sincronización de Threads en Java Monitores en Java: métodos synchronized Los métodos wait y notifyall 23
Threads en Java La clase Thread La cualidad de hilo de ejecución en Java se obtiene por herencia de la clase Thread Creación: realización de subclases de Thread class Reloj extends Thread Código a ejecutar: sobrecargar el método run public void run() {... Otros métodos que se pueden sobrecargar public void start() {... Se ejecuta al arrancar el thread. 24
Threads en Java import java.text.*; import java.util.*; class Reloj extends Thread { int cuenta=0;... public void run() { for (int i = 1; i <= cuenta; i++) { try { sleep(1000); catch (InterruptedException e) { System.out.println(getName() + " : " + (cuenta - i)); System.out.println(getName() + "Riiinnnng!!!"); Concurrent execution accomplished by by inheritance from from the the Thread class class 25
Threads en Java Instanciación e iniciación de Threads public class Relojes { public static void main(string[] args){ new Reloj("MotorOn",10).start(); new Reloj("MotorOff",15).start(); 26
Threads en Java El interfaz Runnable Se utiliza cuando no se puede heredar de la clase Thread por problemas de herencia múltiple. Solución: Implementar Runnable (obliga a sobrecargar run,...) Crear una instancia de Thread y pasarle como agumento el objeto class X extends UnicastRemoteObject implements Runnable { Thread reloj= new Thread(this, "Reloj"); public void run(){ while(this!=null){ f(); try{ Thread.sleep(5); catch(interruptedexception e){ 27
Sincronización de Threads en Java Monitores en Java La sincronización en Java se basa en el concepto de Monitor (de C.A.R. Hoare). TAD: encapsula datos y operaciones. Exclusión mútua en el acceso al monitor: sólo puede haber un proceso activo ejecutando código del monitor. Métodos sincronizados Cuando el control entra en un método sincronizado (synchronized), el thread que lo invocó adquiere el monitor e impide que otros threads puedan ejecutar métodos sincronizados del monitor. 28
Sincronización de Threads en Java Métodos wait y notifyall Existen métodos de la clase Object que permiten realizar esperas condicionales dentro de un monitor. wait() : Suspende el thread hasta que otro thread lo notifica con notifyall() (o notify()). notifyall() : Activa todos los threads suspendidos (con wait()) en el monitor adquirido por el thread que invoca. wait(long timeout) notify() 29
Sincronización de Threads en Java class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int)(math.random() * 100)); catch (InterruptedException e) { 30
Sincronización de Threads en Java class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); 31
Sincronización de Threads en Java class CubbyHole { private int contents; // this is the condition variable. private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); catch (InterruptedException e) { available = false; notifyall(); return contents; public synchronized void put(int value) { while (available == true) { try { wait(); catch (InterruptedException e) { contents = value; available = true; notifyall(); 32
Sincronización de Threads en Java class ProducerConsumerTest { public static void main(string[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); 33