模拟多个人通过一个山洞:这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒,随机生成10个人,同时准备过此山洞,显示一下每次通过山洞人的姓名。

模拟多个人通过一个山洞:这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒,随机生成10个人,同时准备过此山洞,显示一下每次通过山洞人的姓名。

public class 十人过山洞 {
    public static void main(String[] args) {
        people p = new people();

        new Thread(p, "1").start();
        new Thread(p, "2").start();
        new Thread(p, "3").start();
        new Thread(p, "4").start();
        new Thread(p, "5").start();
        new Thread(p, "6").start();
        new Thread(p, "7").start();
        new Thread(p, "8").start();
        new Thread(p, "9").start();
        new Thread(p, "10").start();

    }
}

class people implements Runnable{

    @Override
    public void run() {
        synchronized (people.class) {
            System.out.println(Thread.currentThread().getName());

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Leo_01169/article/details/85755999