【17】编写多线程应用程序,模拟多个人通过一个山洞。山洞每次只能通过一个人,每个人通过山洞的时间为5秒,随机生成10个人,同时准备过此洞,显示每次通过者的姓名。
public class Test
{
public static void main(String[] args)
{
Cave cave=new Cave();
new Thread(cave,"1").start();
new Thread(cave,"2").start();
new Thread(cave,"3").start();
new Thread(cave,"4").start();
new Thread(cave,"5").start();
new Thread(cave,"6").start();
new Thread(cave,"7").start();
new Thread(cave,"8").start();
new Thread(cave,"9").start();
new Thread(cave,"10").start();
}
}
class Cave extends Thread
{
public void run()
{
synchronized(this)
{
System.out.println(Thread.currentThread().getName()+"正在通过,请等待5s");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
随机生成5个人,同时准备过此山洞,显示一下每次通过山洞人的姓名及年龄。
public c