112 lines
3.1 KiB
Java
112 lines
3.1 KiB
Java
import java.awt.Frame;
|
|
import java.awt.Graphics;
|
|
import java.awt.Color;
|
|
import java.awt.image.BufferStrategy;
|
|
import java.util.Vector;
|
|
import java.awt.event.WindowAdapter;
|
|
import java.awt.event.WindowEvent;
|
|
|
|
|
|
public class GoodThreadRun implements Runnable{
|
|
|
|
/**the number of balls we want to have run*/
|
|
public static final int NUMBER_BALLS = 500;
|
|
|
|
/**the frame we are going to draw the balls on*/
|
|
private Frame frame;
|
|
|
|
/**the vector containing all the created balls*/
|
|
private Vector ballVector;
|
|
|
|
/**buffer strategy controlling the draw*/
|
|
private BufferStrategy bufferStrategy;
|
|
|
|
/**the thread controlling the movement of all the balls*/
|
|
private Thread thread;
|
|
|
|
/**boolean indicating the thread is running*/
|
|
private boolean running = true;
|
|
|
|
|
|
public GoodThreadRun() {
|
|
frame = new Frame("Good Thread Example");
|
|
frame.setSize(800, 600);
|
|
frame.setResizable(false);
|
|
frame.setVisible(true);
|
|
frame.addWindowListener(new WindowAdapter() {
|
|
|
|
/** embedded window listener */
|
|
public void windowClosing(WindowEvent we) {
|
|
running = false;
|
|
}
|
|
});
|
|
|
|
|
|
ballVector = new Vector();
|
|
|
|
frame.createBufferStrategy(3);
|
|
bufferStrategy = frame.getBufferStrategy();
|
|
|
|
thread = new Thread(this);
|
|
thread.start();
|
|
|
|
} //end init of good thread run
|
|
|
|
|
|
/**
|
|
starts the simulation
|
|
*/
|
|
public void run() {
|
|
|
|
/**creates the balls that will be running across the screen*/
|
|
for (int i = 0; i < NUMBER_BALLS; i++) {
|
|
ballVector.add(new GoodThreadBall(0, i * 4));
|
|
}
|
|
|
|
/**
|
|
* now we want to draw them again and again and again
|
|
*/
|
|
while (running) {
|
|
/**gets the frame we are drawing on*/
|
|
Graphics g = bufferStrategy.getDrawGraphics();
|
|
|
|
g.setColor(Color.black);
|
|
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
|
|
|
|
g.setColor(Color.red);
|
|
/**draws each circle*/
|
|
for (int i = 0; i < ballVector.size(); i++) {
|
|
GoodThreadBall ball = (GoodThreadBall) ballVector.get(i);
|
|
ball.update();
|
|
g.drawOval(ball.getXPos(), ball.getYPos(), ball.BALL_RADIUS, ball.BALL_RADIUS);
|
|
} //end for
|
|
|
|
g.dispose();
|
|
bufferStrategy.show();
|
|
|
|
try {
|
|
thread.sleep(25);
|
|
} catch (Exception e) {
|
|
System.out.println("error sleeping thread");
|
|
}
|
|
|
|
} //end while
|
|
|
|
System.exit(0);
|
|
|
|
|
|
} //end start
|
|
|
|
|
|
/** runs the example*/
|
|
public static void main(String[] args) {
|
|
|
|
new GoodThreadRun();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} //end class BadThreadRun |