编写多线程程序,模拟多个人通过一个山洞。这个山洞每次只能通过一个人,每个人通过山洞的时间为2秒(sleep)。随机生成10个人,都要通过此山洞,用随机值对应的字符串表示人名,打印输出每次通过山洞的人名。提示:利用线程同步机制,过山洞用一条输出语句表示,该输出语句打印输出当前过山洞的人名,每个人过山洞对应一个线程,哪个线程执行这条输出语句,就表示哪个人过山洞。
代码:
public class 过山洞 {
public static void main (String[] args){
Pass p =new Pass();
new Thread (p,"张三").start();
new Thread (p,"李四").start();
new Thread (p,"王二").start();
new Thread (p,"小黑").start();
new Thread (p,"小红").start();
new Thread (p,"Lisa").start();
new Thread (p,"Mary").start();
new Thread (p,"Tom").start();
new Thread (p,"小狗").start();
new Thread (p,"小猫").start();
}
}
class Pass implements Runnable{
private Object lock=new Object();
public void run(){
synchronized(lock){
System.out.println(Thread.currentThread().getName());
try{
Thread.sleep(2000);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
执行结果: