求一java线程龟兔赛跑的实例!
哪位能帮我解决下线程方面最经典的例子龟兔赛跑吗?谢谢
参考:http://dev.firnow.com/course/3_program/java/javaxl/2008109/149386.html
把图片放在包 t2010070702 下
[code="java"]
package t2010070702;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
/**
- 多线程图形版龟兔赛跑
-
http://dev.firnow.com/course/3_program/java/javaxl/2008109/149386.html
*/
@SuppressWarnings("serial")
public class T 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(), "t2010070702/back.gif");
rabbit = getImage(getCodeBase(), "t2010070702/rabbit.jpg");
tortoise = getImage(getCodeBase(), "t2010070702/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();
}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();
}
}
}
[/code]
[img]http://p.blog.csdn.net/images/p_blog_csdn_net/java2000_net/EntryImages/20081008/back.gif[/img]
[img]http://p.blog.csdn.net/images/p_blog_csdn_net/java2000_net/EntryImages/20081008/rabbit.jpg[/img]
[img]http://p.blog.csdn.net/images/p_blog_csdn_net/java2000_net/EntryImages/20081008/tortoise.jpg[/img]
是不是定义两个线程,每个线程都不断地加一个数,即路程,谁先加到总路程就是谁先到终点。兔子的线程,加到一半时就挂起,到了一定的时间再继续跑。
是这样子不?