• java多线程小练习


    package result;

    //多线程程序,模拟一个台上有多个弹子在上面滚动
    //弹子在碰到台子的边缘是会被弹回来
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    //定义弹子类
    class Marble extends Thread {
    Table table = null;
    // 空引用
    int x, y, xdir, ydir;

    // 弹子的属性,默认为包访问权限
    public Marble(Table _table, int _x, int _y, int _xdir, int _ydir) {
    // 弹子的构造方法
    table = _table;
    // 球台对象指向输入的数据的堆区
    x = _x;
    y = _y;
    // (x,y)坐标
    xdir = _xdir;
    ydir = _ydir;
    // x方向速度,y方向速度
    }

    public void run() {
    while (true) {
    if ((x > (table.getSize().width)) || (x < 0)) {
    xdir *= (-1);
    // 超过台子x方向边界后反方向运行
    // getSize()方法用来求窗体的尺寸
    }
    if ((y > (table.getSize().height)) || (y < 0)) {
    ydir *= (-1);
    }
    x += xdir;
    y += ydir;
    try {
    sleep(30);
    } catch (InterruptedException e) {
    // TODO: handle exception
    System.out.println("Thread interrupted");
    }
    table.repaint();
    }
    }

    public void draw(Graphics g) {
    g.setColor(Color.black);
    // 弹子为黑色
    g.fillOval(x, y, 30, 30);
    // 画圆
    g.setColor(Color.white);
    // 弹子上的亮点为白色
    g.fillOval(x + 5, y + 5, 8, 6);

    }
    }

    //定义球台类
    class Table extends JFrame implements ActionListener {
    /**
    *
    */
    private static final long serialVersionUID = 1L;
    JButton start = new JButton("开始");// Button是awt包中的,具有局限性
    Marble marbles[] = new Marble[5];
    // 建立弹子线程类对象数组
    int v = 2;

    // 速度最小值
    public Table() {
    super("弹子台球");
    setSize(300, 300);
    setBackground(Color.red);
    // 定义背景颜色
    setVisible(true);
    setLayout(new FlowLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    add(start);
    start.addActionListener(this);
    validate();
    }

    public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    for (int i = 0; i < marbles.length; i++) {
    // 随机产生弹子的速度和坐标
    int xdir = i * (1 - i * (int) Math.round(Math.random())) + v;
    int ydir = i * (1 - i * (int) Math.round(Math.random())) + v;
    int x = (int) (getSize().width * Math.random());
    int y = (int) (getSize().height * Math.random());
    // 实例化弹子线程对象
    marbles[i] = new Marble(this, x, y, xdir, ydir);
    marbles[i].start();
    }
    }

    public void paint(Graphics g) {
    for (int i = 0; i < marbles.length; i++) {
    if (marbles[i] != null) {
    marbles[i].draw(g);
    }
    }
    }
    }

    public class F9 {
    public static void main(String[] arg) {
    new Table();
    }
    }

  • 相关阅读:
    Java事务
    Mybatis二级缓存问题
    183.面试题 17.14. 最小K个数(快速排序)
    182. 跟着三叶学最短路径问题(存图方式)
    181. 差分数组学习
    AI大视觉(二十) | 小目标检测的tricks汇总
    CentOS7 上安装 mysql-5.7.26
    如何欺骗 Go Mod?
    .netcore docker常用命令-持续补充
    转载:登录后,用户配置被修改的处理方法
  • 原文地址:https://www.cnblogs.com/nanfengnan/p/13675184.html
Copyright © 2020-2023  润新知