Ciclo de Vida de um Thread

Introdução

threads-states.gif (5424 bytes)

Criação de um thread

    public void start() {
        if (clockThread == null) {
            clockThread = new Thread(this, "Clock");
            clockThread.start();
        }
    }

Iniciando um thread

    public void start() {
        if (clockThread == null) {
            clockThread = new Thread(this, "Clock");
            clockThread.start();
        }
    }
    public void run() {
        Thread myThread = Thread.currentThread();
        while (clockThread == myThread) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // The VM doesn't want us to sleep anymore,
                // so get back to work
            }
        }
    }
    public void paint(Graphics g) {
        //get the time and convert it to a date
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        //format it and display it
        DateFormat dateFormatter = DateFormat.getTimeInstance();
        g.drawString(dateFormatter.format(date), 5, 10);
    }

O estado Non-Runnable

    public void run() {
        Thread myThread = Thread.currentThread();
        while (clockThread == myThread) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
               // The VM doesn't want us to sleep anymore,
               // so get back to work
            }
        }
    }

Parando um thread

    public void run() {
        int i = 0;
        while (i < 100) {
            i++;
            System.out.println("i = " + i);
        }
    }
    public void stop() {    // applets' stop method
        clockThread = null;
    }

Testando o estado de um thread

programa