描述:
请按要求编写多线程应用程序,模拟多个人通过一个山洞:
这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒。
随机生成10个人,同时准备过此山洞,显示每次通过山洞人的姓名。
public class Test01 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Cross thread = new Cross(i + "号选手");
thread.start();
}
}
}
class Cross extends Thread{
//定义一个变量,记录通过隧道的人数
private static int count = 0;
public Cross(String name) {
super(name);
}
@Override
public void run() {
synchronized (Cross.class){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println(Thread.currentThread().getName()+"已经通过隧道,是第"+count+"个人");
}
}
}
原文:https://www.cnblogs.com/liqiliang1437/p/13112166.html