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();
}
}
显示结果: