aula03TPararThreads

import java.io.IOException;

class StopMe extends Thread {
    private boolean stopRunning = false;

    public void setStop(boolean stopRunning) {
        this.stopRunning = stopRunning;
    }

    public void run() {
        int count = 1;
        System.out.println("I can count. Watch me go!");
        for (; ; ) {
            if (stopRunning) return;
            System.out.print(count++ + " ");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
        }
    }
}

//sem forçar a terminar uma thread, abordagem correta
public class aula03PararThreads {

    public static void main(String[] args) throws IOException {
        Thread counter = new StopMe();
        counter.start();
        System.out.println ("Press any enter to stop the thread counting");
        System.in.read();
        ((StopMe) counter).setStop(true);
    }
}
Tags : ,

0 thoughts on “aula03TPararThreads”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.