计算机软件实验报告
课程名称:JAVA 程序设计
姓
名 李兆明 学 号
11
班 级
0820541
成 绩
设备名称及软件环境
MyEclipse
实验名称
Java Applet 技术
实验日期
2011-10-24
一.实验内容:
调试 P300 的例题 13.11
二.重点及难点
编写一个龟兔赛跑的多线程程序。
三.实现方法(含实现思路、程序流程图和源程序列表等)
package com.java1018.struts;
// 龟兔赛跑
public class Test extends JApplet implements Runnable {
Image backpic, rabbit, tortoise;
int x1 = 0, y1 = 0;
int x2 = 0, y2 = 100;
int rab_road = 0, tor_road = 0;
int rab_time = 0, tor_time = 0;
String str1 = "rabbit", str2 = "tortoise";
public void init() {
setSize(700, 200);
backpic = getImage(getCodeBase(), "back.gif");
rabbit = getImage(getCodeBase(), "rabbit.jpg");
tortoise = getImage(getCodeBase(), "tortoise.jpg");
}
}
public void paint(Graphics g) {
g.drawImage(backpic, 0, 0, 700, 200, this);
g.drawImage(rabbit, x1, y1, 60, 60, this);
g.drawString(str1, x1, y1 + 80);
g.drawImage(tortoise, x2, y2, 60, 60, this);
g.drawString(str2, x2, y2 + 80);
public void start() {
Thread rab = new Thread(this, "rabbit");
Thread tor = new Thread(this, "tortoise");
rab.start();
tor.start();}
1
public void run() {
boolean stop = false;
while (!stop) {
try {Thread.sleep(100);
} catch (InterruptedException ex) {}
String threadName = Thread.currentThread().getName();
if (threadName.equals("rabbit")) {
str1 = "rabbit"; x1 = x1 + 30; rab_time++; rab_road += 3;
if (rab_road % 24 == 0) {
str1 = "兔子睡眠";
try { Thread.sleep(2400);
} catch (InterruptedException ex) {}
rab_time += 24;
}
if (rab_road == 60) {
stop = true;
str1 = "兔子总共用时间(秒):" + rab_time;
}
} else if (threadName.equals("tortoise")) {
x2 += 10; tor_road += 1; tor_time++;
if (tor_road == 60) {
stop = true;
str2 = "乌龟总共用时间(秒):" + tor_time;
repaint();
}}
}
}
}
四.实验结果分析(含执行结果验证、输出显示信息、图形、调试过程中所遇的问题及处理方法等)
报告提交日期
2011-10-25
2
3