java 小编程100题

编写多线程应用程序,模拟多个人通过一个山洞:

2017-09-18  本文已影响0人  阿狸演绎

1、编写多线程应用程序,模拟多个人通过一个山洞:
(1)这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒
(2)随机生成10个人,同时准备过此山洞,显示一下每次通过山洞人的姓名
思路:一个山洞(类),10个人(10个线程),只有一个人能通过(当一个线程通过时没其他线程不能运行这个程序,线程锁),
通过时间5秒,即线程sleep 5秒

public class Test02 {
  
    public static void main(String[] args) {
        //实例化山洞
        Shandong shandong = new Shandong();
        //创建10个线程
        Thread thread1 = new Thread(shandong, "1");
        Thread thread2 = new Thread(shandong, "2");
        Thread thread3 = new Thread(shandong, "3");
        Thread thread4 = new Thread(shandong, "4");
        Thread thread5 = new Thread(shandong, "5");
        Thread thread6 = new Thread(shandong, "6");
        Thread thread7 = new Thread(shandong, "7");
        Thread thread8 = new Thread(shandong, "8");
        Thread thread9 = new Thread(shandong, "9");
        Thread thread10 = new Thread(shandong, "10");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        thread6.start();
        thread7.start();
        thread8.start();
        thread9.start();
        thread10.start();
    
         
        
    }
}
//山洞
class Shandong extends Thread{
    @Override
    public void run() {
    //上锁
        synchronized(this){
            System.out.println(Thread.currentThread().getName()+"正在通过,请等待5s");
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读