您的位置:首页 > 编程语言 > Java开发

Java多线程-两个小球

2015-11-27 21:58 417 查看
import java.applet.*;
import java.awt.*;
import javax.swing.*;

public class MyBall {
public static void main(String[] args) {
JFrame w = new JFrame();
w.setSize(300, 400);
MyPanel mp = new MyPanel();
w.add(mp);
Thread b1 = new Thread(mp, "b1");
Thread b2 = new Thread(mp, "b2");
b1.start();
b2.start();
w.show();
}
}

class MyPanel extends JPanel implements Runnable {
int gx = 40, gy = 30, tx = 60, ty = 30;
String str1 = "b1", str2 = "b2";

public void run() {
boolean stop = false;
while (!stop) {
String s = Thread.currentThread().getName().toString();
if (s.equals(str1)) {
gy++;
try {
Thread.sleep(60);
} catch (Exception e) {
}
if (gy >= 200)
stop = true;
} else {
ty++;
try {
Thread.sleep(30);
} catch (Exception e) {
}
if (ty >= 200)
stop = true;
}
repaint();
}
}

public void paint(Graphics g) {
super.paint(g);
g.fillOval(gx, gy, 20, 20);
g.fillOval(tx, ty, 20, 20);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: