多线程图形版龟兔赛跑

运行效果:

源代码
  1. import java.awt.Graphics;
  2. import java.awt.Image;
  3. import javax.swing.JApplet;
  4. /**
  5.  * 
  6.  * @author 万春丽,赵学庆 java2000.net
  7.  *
  8.  */
  9. public class T extends JApplet implements Runnable {
  10.   Image backpic, rabbit, tortoise;
  11.   int x1 = 0, y1 = 0;
  12.   int x2 = 0, y2 = 100;
  13.   int rab_road = 0, tor_road = 0;
  14.   int rab_time = 0, tor_time = 0;
  15.   String str1 = "rabbit", str2 = "tortoise";
  16.   public void init() {
  17.     setSize(700200);
  18.     backpic = getImage(getCodeBase(), "back.gif");
  19.     rabbit = getImage(getCodeBase(), "rabbit.jpg");
  20.     tortoise = getImage(getCodeBase(), "tortoise.jpg");
  21.   }
  22.   public void paint(Graphics g) {
  23.     g.drawImage(backpic, 00700200this);
  24.     g.drawImage(rabbit, x1, y1, 6060this);
  25.     g.drawString(str1, x1, y1 + 80);
  26.     g.drawImage(tortoise, x2, y2, 6060this);
  27.     g.drawString(str2, x2, y2 + 80);
  28.   }
  29.   public void start() {
  30.     Thread rab = new Thread(this"rabbit");
  31.     Thread tor = new Thread(this"tortoise");
  32.     rab.start();
  33.     tor.start();
  34.   }
  35.   public void run() {
  36.     boolean stop = false;
  37.     while (!stop) {
  38.       try {
  39.         Thread.sleep(100);
  40.       } catch (InterruptedException ex) {
  41.       }
  42.       String threadName = Thread.currentThread().getName();
  43.       if (threadName.equals("rabbit")) {
  44.         str1 = "rabbit";
  45.         x1 = x1 + 30;
  46.         rab_time++;
  47.         rab_road += 3;
  48.         if (rab_road % 24 == 0) {
  49.           str1 = "兔子睡眠";
  50.           try {
  51.             Thread.sleep(2400);
  52.           } catch (InterruptedException ex) {
  53.           }
  54.           rab_time += 24;
  55.         }
  56.         if (rab_road == 60) {
  57.           stop = true;
  58.           str1 = "兔子总用时(秒):" + rab_time;
  59.         }
  60.       } else if (threadName.equals("tortoise")) {
  61.         x2 += 10;
  62.         tor_road += 1;
  63.         tor_time++;
  64.         if (tor_road == 60) {
  65.           stop = true;
  66.           str2 = "乌龟总用时(秒):" + tor_time;
  67.         }
  68.       }
  69.       repaint();
  70.     }
  71.   }
  72. }

几个图片


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值