編寫多執行緒應用程式,模擬多個人通過一個山洞:

weixin_34185364發表於2017-09-18

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();
            }
        }
    }
}

相關文章