java多线程例子-赛马

2014-07-22· 5551 次浏览
## 效果图 ![TIM截图20180508205159.bmp](https://image.xsoftlab.net/baike/articleImages/4e9dd8a362282aa84d9f99db3be9197b.jpg) ## 介绍 例子很简洁,只有两个类,一个是马类(Horse),一个是窗体类(GameFrame),程序入口写在了GameFrame中,每匹马都有一个独立的线程控制移动,东西不多,很容易理解。 ## 准备工作 只需要一张动态图horse2.gif,就是奔跑的马。 ![horse](http://www.zhenzhigu.com/attachment/1405/thread/6_2_e62bfa4c042c69c.gif) ## 代码 ### Horse 类 ```java package com.zhenzhigu.race; import java.awt.Point; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; /**  * 马  *   * @author loopcc create 20140514  *  */ public class Horse extends JLabel implements Runnable {     public int speed = 1;// 移动速度     public Icon icon = new ImageIcon("d:/horse2.gif");     /**      * 构造方法,指定坐标与速度      *       * @param x      * @param y      * @param speed      */     public Horse(int x, int y, int speed) {         this.setBounds(x, y, 222, 222);         this.speed = speed;         this.setIcon(icon);         // 新开一个线程并启动         new Thread(this).start();     }     @Override     public void run() {         Point p = null;         while (true) {             try {                 p = this.getLocation();                 this.setLocation(p.x - speed, p.y);                 // 每隔33毫秒移动一次                 Thread.sleep(33);             } catch (Exception e) {                 e.printStackTrace();             }         }     } } ``` ### GameFrame 类 ```java package com.zhenzhigu.race; import javax.swing.JFrame; /**  * 程序主窗体  *   * @author loopcc  *  */ public class GameFrame extends JFrame {     public GameFrame() {         this.setLayout(null);// 设置布局为null         this.setSize(999, 650);// 设置窗体大小         this.setVisible(true);// 设置窗体显示         this.setDefaultCloseOperation(EXIT_ON_CLOSE);// 设置关闭规则         this.setTitle("多线程Demo - 赛马 - 【真知谷科技:www.zhenzhigu.com】");     }     /**      * 程序入口      *       * @param a      */     public static void main(String a[]) {         GameFrame game = new GameFrame();         game.add(new Horse(900, 50, 1));// 新建一匹马并添加到game窗体中         game.add(new Horse(900, 200, 3));         game.add(new Horse(900, 350, 2));     } } ``` ## 原文地址 [http://www.zhenzhigu.com/read.php?tid=28&fid=6](http://www.zhenzhigu.com/read.php?tid=28&fid=6)