Safely stopping a thread

K

Kevin Jennings

Hi, group! I bought a book, "Black Art of Game Programming in Java" and
I've started typing in some of the programs. The book is pretty old,
apparently, and very outdated. One of the initial programs uses a
deprecated method (thread.stop). Can someone look at the code below and
tell me the correct way this thread should be ended without me having to use
the deprecated method?

Thanks so much!!!

Kevin

import java.applet.*;
import java.awt.*;

public class Broadway extends Applet implements Runnable {

Graphics offscreen;
Image image;
Thread animation;
int locx, locy;
int width, height;

static final byte UP = 0;
static final byte DOWN = 1;
static final byte LEFT = 2;
static final byte RIGHT = 3;

byte state;

static final int REFRESH_RATE = 100;

public void init() {

System.out.println(">> init << ");
setBackground(Color.black);
locx = 80;
locy = 100;
width = 110;
height = 90;
state = UP;

image = createImage(300,300);
offscreen = image.getGraphics();
}

public void start() {
System.out.println(">> start <<");
animation = new Thread(this);
if (animation != null) {
animation.start();
}
}

public void paint(Graphics g) {

offscreen.setColor(Color.black);
offscreen.fillRect(0,0,300,300);

offscreen.setColor(Color.yellow);
offscreen.fillRect(0,0,90,90);
offscreen.fillRect(250,0,40, 190);
offscreen.fillRect(80, 110, 100,20);

offscreen.setColor(Color.blue);
offscreen.fillRect(80,200,220,90);
offscreen.fillRect(100, 10,90,80);

offscreen.setColor(Color.green);
offscreen.fillRect(locx, locy, width, height);

offscreen.setColor(Color.red);
offscreen.fillRect(200,0,45,45);
offscreen.fillRect(0,100,70,200);

offscreen.setColor(Color.magenta);
offscreen.fillRect(200,55,60,135);
g.drawImage(image,0,0,this);
}

void updateRectangle() {
switch(state) {
case DOWN:
locy +=2;
if (locy >= 110) {
state = LEFT;
}
break;

case UP:
locy -= 2;
if (locy <= 90) {
state = RIGHT;
}
break;

case RIGHT:
locx += 2;
if (locx >= 90) {
state = DOWN;
}
break;

case LEFT:
locx -= 2;
if (locx <= 70) {
state = UP;
}
break;
}
}

public void run() {
while(true) {
repaint();
updateRectangle();
try {
Thread.sleep(REFRESH_RATE);
} catch (Exception exc) { };

}
}

public void update(Graphics g) {
g.clipRect(70,90,130,110);
paint(g);
}

public void stop() {
System.out.println(">> stop <<");
if (animation != null) {
animation.stop();
animation = null;
}
}
}
 
K

Kevin Jennings

Whoops! Sorry! I meant to post this to comp.lang.java.help! Please
disregard!

Thanks,

Kevin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top