Você está na página 1de 14

Multitarea e Hilos en Java con ejemplos

(Thread & Runnable)


Ejercicio # 1
// Definimos unos sencillos hilos. Se detendrn un rato
// antes de imprimir sus nombres y retardos
class TestTh extends Thread {
private String nombre;
private int retardo;
// Constructor para almacenar nuestro nombre
// y el retardo
public TestTh( String s,int d ) {
nombre = s;
retardo = d;
}
// El metodo run() es similar al main(), pero para
// threads. Cuando run() termina el thread muere
public void run() {
// Retasamos la ejecucin el tiempo especificado
try {
sleep( retardo );
} catch( InterruptedException e ) {
;
}

// Ahora imprimimos el nombre


System.out.println( "Hola Mundo! "+nombre+" "+retardo );
}

public class MultiHola {


public static void main( String args[] ) {
TestTh t1,t2,t3;
// Creamos los threads
t1 = new TestTh( "Thread 1",(int)(Math.random()*2000) );
t2 = new TestTh( "Thread 2",(int)(Math.random()*2000) );
t3 = new TestTh( "Thread 3",(int)(Math.random()*2000) );

// Arrancamos los threads


t1.start();
t2.start();
t3.start();
}

Ejercicio # 2

Arrancar y Parar Threads


import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class NOMBRECLASE extends Applet implements Runnable {
Thread t;
int contador;
// Creamos el thread y lo arrancamos
public void init() {
ProcesoRaton procesoRaton = new ProcesoRaton();
addMouseListener( procesoRaton );
contador = 0;
t = new Thread( this );
t.start();
}
// Corazn del applet, incrementa el contador, lo pinta en la
// pantalla y tiene su tiempo de espera, tanto para incrementar
// de nuevo el contador como para dejar tiempo a la CPU para que
// atienda a otros applets o aplicaciones que pudiesen convivir
public void run() {
Thread miThread = Thread.currentThread();
while( t == miThread )
{
contador++;
repaint();
// Forzosamente tenemos que capturar esta interrupcin
try {
miThread.sleep( 10 );
} catch( InterruptedException e ) {
;
};
}
}
// Actualizamos un contador en la ventana del applet y otro en
// la consola
public void paint( Graphics g ) {
g.drawString( Integer.toString( contador ),10,10 );
System.out.println( "Contador= "+contador );
}
// Paramos el applet, pero sin llamar al mtodo stop()
public void stop() {
t = null;
}

// Cuando se pulsa el ratn dentro del dominio del applet


// se detiene la ejecucin
// Esta es una Clase Anidada
class ProcesoRaton extends MouseAdapter {
public void mousePressed( MouseEvent evt ) {
t.stop();
}
}
}

Ejercicio # 3

package threadsJarroba;
/**
*
* @author Richard
*/
public class Cajera {
private String nombre;
public Cajera() {
}
public Cajera(String nombre) {
this.nombre = nombre;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void procesarCompra(Cliente cliente, long timeStamp) {
System.out.println("La cajera " + this.nombre +
" COMIENZA A PROCESAR LA COMPRA DEL CLIENTE " +
cliente.getNombre() +
" EN EL TIEMPO: " + (System.currentTimeMillis() timeStamp) / 1000 +
"seg");
for (int i = 0; i < cliente.getCarroCompra().length; i++) {
this.esperarXsegundos(cliente.getCarroCompra()[i]);
System.out.println("Procesado el producto " + (i + 1) +
" ->Tiempo: " + (System.currentTimeMillis() timeStamp) / 1000 +
"seg");
}
System.out.println("La cajera " + this.nombre + " HA TERMINADO DE
PROCESAR " +
cliente.getNombre() + " EN EL
TIEMPO: " +
(System.currentTimeMillis() timeStamp) / 1000 + "seg");
}
private void esperarXsegundos(int segundos) {
try {
Thread.sleep(segundos * 1000);

} catch (InterruptedException ex) {


Thread.currentThread().interrupt();
}

Ejercicio # 4
package threadsJarroba;
/**
*

* @author Richard
*/
public class CajeraThread extends Thread {
private String nombre;
private Cliente cliente;
private long initialTime;
public CajeraThread() {
}
public CajeraThread(String nombre, Cliente cliente, long initialTime) {
this.nombre = nombre;
this.cliente = cliente;
this.initialTime = initialTime;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public long getInitialTime() {
return initialTime;
}
public void setInitialTime(long initialTime) {
this.initialTime = initialTime;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
@Override
public void run() {
System.out.println("La cajera " + this.nombre + " COMIENZA A
PROCESAR LA COMPRA DEL CLIENTE "
+ this.cliente.getNombre() + " EN EL TIEMPO: "
+ (System.currentTimeMillis() - this.initialTime) /
1000
+ "seg");
for (int i = 0; i < this.cliente.getCarroCompra().length; i++) {

// Se procesa el pedido en X segundos


this.esperarXsegundos(cliente.getCarroCompra()[i]);
System.out.println("Procesado el producto " + (i + 1)
+ " del cliente " + this.cliente.getNombre()
+ "->Tiempo: "
this.initialTime) / 1000

+ (System.currentTimeMillis() + "seg");

}
PROCESAR "

System.out.println("La cajera " + this.nombre + " HA TERMINADO DE

TIEMPO: "
this.initialTime) / 1000
}

+ this.cliente.getNombre() + " EN EL
+ (System.currentTimeMillis() + "seg");

private void esperarXsegundos(int segundos) {


try {
Thread.sleep(segundos * 1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}

Ejercicio # 4
package threadsJarroba;
/**
*

* @author Richard
*/
public class Cliente {
private String nombre;
private int[] carroCompra;
public Cliente() {
}
public Cliente(String nombre, int[] carroCompra) {
this.nombre = nombre;
this.carroCompra = carroCompra;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int[] getCarroCompra() {
return carroCompra;
}
public void setCarroCompra(int[] carroCompra) {
this.carroCompra = carroCompra;
}
}

Ejercicio # 5
package threadsJarroba;
/**

*
* @author Richard
*/
public class Main {
public static void main(String[] args) {
Cliente cliente1 = new Cliente("Cliente 1", new int[] { 2, 2, 1, 5, 2, 3 });
Cliente cliente2 = new Cliente("Cliente 2", new int[] { 1, 3, 5, 1, 1 });
Cajera cajera1 = new Cajera("Cajera 1");
Cajera cajera2 = new Cajera("Cajera 2");
// Tiempo inicial de referencia
long initialTime = System.currentTimeMillis();
cajera1.procesarCompra(cliente1, initialTime);
cajera2.procesarCompra(cliente2, initialTime);
}

Ejercion # 6
Este es un ejemplo de un applet, crea un hilo de animacin que nos presenta el
globo terrqueo en rotacin. Aqu se puede ver que el applet crea un hilo de
ejecucin de s mismo (concurrencia). Adems, animacion.start() llama
al start() del hilo, no del applet, que automticamente llamar a run():

import java.awt.*;
import java.applet.Applet;
public class NOMBRECLASE extends Applet implements Runnable {
Image imagenes[];
MediaTracker tracker;
int indice = 0;
Thread animacion;
int maxAncho,maxAlto;
Image offScrImage; // Componente off-screen para doble buffering
Graphics offScrGC;
// Nos indicar si ya se puede pintar
boolean cargado = false;
// Inicializamos el applet, establecemos su tamao y
// cargamos las imgenes
public void init() {
// Establecemos el supervisor de imgenes
tracker = new MediaTracker( this );
// Fijamos el tamao del applet
maxAncho = 100;
maxAlto = 100;
imagenes = new Image[18];
// Establecemos el doble buffer y dimensionamos el applet
try {
offScrImage = createImage( maxAncho,maxAlto );
offScrGC = offScrImage.getGraphics();
offScrGC.setColor( Color.lightGray );
offScrGC.fillRect( 0,0,maxAncho,maxAlto );
resize( maxAncho,maxAlto );
} catch( Exception e ) {
e.printStackTrace();
}
// Cargamos las imgenes en un array
for( int i=0; i < 18; i++ )
{
String fichero =
new String( "tierra"+String.valueOf(i+1)+".gif" );
imagenes[i] = getImage( getDocumentBase(),fichero );
// Registramos las imgenes con el tracker
tracker.addImage( imagenes[i],i );
showStatus( "Cargando Imagen: "+fichero );
}
showStatus( "" );
try {
// Utilizamos el tracker para comprobar que todas las
// imgenes estn cargadas
tracker.waitForAll();
} catch( InterruptedException e ) {
;
}

cargado = true;
}
// Pintamos el fotograma que corresponda
public void paint( Graphics g ) {
if( cargado )
g.drawImage( offScrImage,0,0,this );
}
// Arrancamos y establecemos la primera imagen
public void start() {
if( tracker.checkID( indice ) )
offScrGC.drawImage( imagenes[indice],0,0,this );
animacion = new Thread( this );
animacion.start();
}
// Aqu hacemos el trabajo de animacin
// Muestra una imagen, para, muestra la siguiente...
public void run() {
// Obtiene el identificador del thread
Thread thActual = Thread.currentThread();
// Nos aseguramos de que se ejecuta cuando estamos en un thread
// y adems es el actual
while( animacion != null && animacion == thActual )
{
if( tracker.checkID( indice ) )
{
// Obtenemos la siguiente imagen
offScrGC.drawImage( imagenes[indice],0,0,this );
indice++;
// Volvemos al principio y seguimos, para el bucle
if( indice >= imagenes.length )
indice = 0;
}
// Ralentizamos la animacin para que parezca normal
try {
animacion.sleep( 200 );
} catch( InterruptedException e ) {
;
}
// Pintamos el siguiente fotograma
repaint();
}
}

Ejercicio # 7
package aplicacionhilos;
/**
*
* @author usuario
*/
public class animal extends Thread {

String nombre;
int limite;
public animal(String nombre, int limite){
this.nombre = nombre;
this.limite = limite;
}
@Override
public void run(){
for (int n=0; n<limite;n++) {
System.out.println(nombre+" avanza");
}
System.out.println(nombre+" ha llegado a la meta");
yield();

}
}

package aplicacionhilos;
/**
*
* @author usuario
*/
public class Aplicacionhilos {
/**
* @param args the command line arguments
*/

public static void main(String[] args) {


animal conejo= new animal("conejo", 100);
animal tortuga= new animal("tortuga", 100);
animal perro=new animal("perro", 100);
conejo.start();
tortuga.start();
perro.start();
//System.out.println("La carrera ha terminado");
}
}

Ejercicio # 8
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package aplicacionhilos;
import
import
import
import

java.util.logging.Level;
java.util.logging.Logger;
javax.swing.JLabel;
javax.swing.JOptionPane;

/**
*
* @author usuario
*/
public class animal extends Thread {
String nombre;
int limite;
JLabel Etiqueta;
public animal(String nombre, int limite, JLabel Etiqueta){
this.nombre = nombre;
this.limite = limite;
this.Etiqueta= Etiqueta;
}
@Override
public void run(){
for (int n=0; n<limite;n++) {
try {
System.out.println(nombre+" avanza");
Etiqueta.setLocation(n,0);
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(animal.class.getName()).log(Level.SEVERE, null,
ex);
}
}
//System.out.println(nombre+" ha llegado a la meta");
JOptionPane.showMessageDialog(null, nombre +" Ha llegado a la meta");
System.out.println(nombre +" Ha llegado a la meta");
yield();

}
}

Você também pode gostar