编写多线程程序,模拟多个人通过一个山洞。这个山洞每次只能通过一个人,每个人通过山洞的时间为2秒(sleep)。随机生成10个人,都要通过此山洞,用随机值对应的字符串表示人名,打印输出每次

来源:互联网 发布:中国移动网络大厅 编辑:程序博客网 时间:2024/06/09 14:25
class Cave implements Runnable{Object lock=new Object();//定义任意一个对象,用作同步代码块的锁的public  void run(){synchronized(lock){ //定义同步代码块System.out.println(Thread.currentThread().getName()+" 通过山洞");  try{ Thread.sleep(2000) ;    }catch(InterruptedException e){   e.printStackTrace();   }}}}public class Example {public static void main(String[] args) {Cave cave =new Cave();//创建对象for(int i=0;i<10;i++)        new Thread(cave,"lucy"+(int)((Math.random()*100))).start();       }}

显示结果:

阅读全文
0 0