多重スレッド
public void tstop() {
cont = false;
}
import java.awt.*;
public class Ball extends Thread {
int w = 15;
int h = 15;
int x = 0;
int y = 0;
int dx = 2;
int dy = 2;
boolean cont = true;
public Ball(int dx, int dy, int w, int h) {
this.w = w;
this.h = h;
this.dx = dx;
this.dy = dy;
}
public void run() {
while (cont) {
move();
try {
sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
void draw(Graphics g) {
//System.out.println("draw ball");
g.fillOval(x, y, 5, 5);
}
public void move() {
x += dx;
y += dy;
if (x <= 0) {
x = 0;
dx = -dx;
}
if (x >= w) {
x=w;
dx = -dx;
}
if (y <= 0) {
y = 0;
dy = -dy;
}
if (y >= h) {
y = h;
dy = -dy;
}
}
public void tstop() {
cont = false;
}
}
ここにソースがあります。w = this.getWidth(); h = this.getHeight(); ball1 = new Ball(1, 2, w, h); ball1.start();同様に、ball2,ball3 のスレッドも起動し、最後に、
public void paint(Graphics g) {
ball1.draw(g);
ball2.draw(g);
ball3.draw(g);
}
import java.applet.Applet;
import java.awt.*;
//<APPLET CODE="MultiThread.class" WIDTH=250 HEIGHT=250></APPLET>
public class MultiThread extends Applet implements Runnable {
Ball ball1, ball2, ball3;
int w, h;
Thread drawBall;
boolean cont = true;
public void init() {
w = this.getWidth();
h = this.getHeight();
ball1 = new Ball(1, 2, w, h);
ball1.start();
ball2 = new Ball(2, 1, w, h);
ball2.start();
ball3 = new Ball(3, 2, w, h);
ball3.start();
drawBall = new Thread(this);
drawBall.start();
}
public void run() {
while (cont) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
public void paint(Graphics g) {
ball1.draw(g);
ball2.draw(g);
ball3.draw(g);
}
public void stop() {
cont = false;
ball1.tstop();
ball2.tstop();
ball3.tstop();
}
}
ここにソースがあります。このクラスを実行するには Ball クラスを必要です。Jcpad上で このソースだけでなく、ファイルメニューから新規作成し、Ball.java
のソースも組み込み、同じフォルダに保存します。MultiThread.java をコンパイルすると、Ball.java も同時にコンパイルされます。