Threads de Control

El RaceApplet utiliza un m�todo del AWT caducado (size) y el antiguo mecanismo de gesti�n de ventos. Aqu� tienes la nueva versi�n para el JDK 1.1 del applet RaceApplet utilizando el nuevo m�todo getSize y el nuevo esquema de manejo de eventos.

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class RaceApplet1_1 extends java.applet.Applet implements Runnable {

    final static int NUMRUNNERS = 2;
    final static int SPACING = 20;

    Runner[] runners = new Runner[NUMRUNNERS];

    Thread updateThread = null;

    public void init() {
        String raceType = getParameter("type");
        for (int i = 0; i < NUMRUNNERS; i++) {
            runners[i] = new Runner();
            if (raceType.compareTo("unfair") == 0)
                    runners[i].setPriority(i+2);
            else
                    runners[i].setPriority(2);
        }
        if (updateThread == null) {
            updateThread = new Thread(this, "Thread Race");
            updateThread.setPriority(NUMRUNNERS+2);
        }
        addMouseListener(new MyAdapter());
    }

    class MyAdapter extends MouseAdapter {
        public void mouseClicked(MouseEvent evt) {
            if (!updateThread.isAlive())
                updateThread.start();
            for (int i = 0; i < NUMRUNNERS; i++) {
                if (!runners[i].isAlive())
                    runners[i].start();
            }
        }
    }

    public void paint(Graphics g) {
        g.setColor(Color.lightGray);
        g.fillRect(0, 0, getSize().width, getSize().height);
        g.setColor(Color.black);
        for (int i = 0; i < NUMRUNNERS; i++) {
            int pri = runners[i].getPriority();
            g.drawString(new Integer(pri).toString(), 0, (i+1)*SPACING);
        }
        update(g);
    }

    public void update(Graphics g) {
        for (int i = 0; i < NUMRUNNERS; i++) {
            g.drawLine(SPACING, (i+1)*SPACING, SPACING + (runners[i].tick)/1000, (i+1)*SPACING);
        }
    }

    public void run() {
        while (Thread.currentThread() == updateThread) {
            repaint();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
        }
    }    

    public void stop() {
        for (int i = 0; i < NUMRUNNERS; i++) {
            if (runners[i].isAlive()) {
                runners[i] = null;
            }
        }
        if (updateThread.isAlive()) {
            updateThread = null;
        }
    }
}

Y aqu� tienes el RaceApplet realizando una carrera trucada.

Y una carrera justa.

Puedes ver Cambios en el GUI: El AWT Crece para m�s informaci�n sobre �ste y otros cambios en el AWT.

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP
ARTÍCULO ANTERIOR

SIGUIENTE ARTÍCULO