一、题目描述
1(题目编号7179)、利用多线程技术编写一个模拟龟兔赛跑的程序,要求如下:(1)乌龟每次跑一个单位,兔子每次跑10个单位;(2)每个线程运行时,判断是否达到终点,如果到达终点,给出提示信息,未到终点则提示目前距离终点的距离,并判断是否领先;(3)如果兔子领先,则显示“我跑得快,睡一觉”信息,并睡一会。
2(题目编号8690)、编写多线程应用程序,模拟多人过独木桥的模拟。独木桥每次只能通过一个人,每个人通过木桥的时间为5秒,随机生成10个人,同时准备过此独木桥,显示一下每次通过独木桥人的姓名。需要用到随机数。
3(题目编号7180)、哈尔滨火车站下面有三个火车票代售点:哈站、哈东站、哈西站,假如哈尔滨到北京的火车票总共是200张,如何用程序来实现三个售票点同时卖票的功能。注意:考虑线程同步问题,避免出现重复卖票问题。需要考虑同步问题。
二、代码实现
题目一内容:
class Player implements Runnable{
private int j=1000;
private int w=0;
private int t=0;
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
if("乌龟".equals(Thread.currentThread().getName())) {
w=w+1;
if(w>j) {
System.out.println("乌龟到达终点");
break;
}
else {
System.out.println("乌龟距离终点"+(j-w));
}
}
else {
if("兔子".equals(Thread.currentThread().getName())) {
t=t+10;
if(t>j) {
System.out.println("兔子到达终点");
break;
}
else {
System.out.println("兔子距离终点"+(j-t));
}
if(t>w)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("我跑得快,睡一觉");
}
}
}
}
}
}
public class Main {
public static void main(String[] args){
Player player=new Player();
Thread wt=new Thread(player,"乌龟");
Thread tt =new Thread(player,"兔子");
wt.start();
tt.start();
}
}
题目二内容:
import java.util.HashSet;
import java.util.Set;
class People implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(this) {
System.out.println(Thread.currentThread().getName()+"正在过桥");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"已通过桥");
}
}
}
public class Main2 {
public static void main(String[] args) {
String[] name= {"一","二","三","四","五","六","七","八","九","十"};
Set<Integer> set=new HashSet<Integer>();
while(set.size()<10) {
set.add((int)(Math.random()*10));
}
People people =new People();
for(int a:set) {
Thread thread =new Thread(people,name[a]);
thread.start();
}
}
}
题目三内容:
class Sta implements Runnable{
private int num=200;
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
synchronized(this) {
System.out.println(Thread.currentThread().getName()+"正在售票"+num);
num--;
if(num<=0)
break;
}
}
}
}
public class Main3 {
public static void main(String[] args) {
Sta sta=new Sta();
Thread x=new Thread(sta,"哈西");
Thread d=new Thread(sta,"哈东");
Thread h=new Thread(sta,"哈站");
x.start();
d.start();
h.start();
}
}