Java多线程-两个小球

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);
    }
}
原文地址:https://www.cnblogs.com/zuferj115/p/5001847.html