Java基础--多线程--练习(过隧道)

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

1、 这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒

2、随机生成10个人,同时准备过此山洞,显示一下每次通过山洞人的姓名

 

MuThreadTest.java

package com.Train;

public class MuThreadTest{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //创建一个山洞
        Tunnel tul = new Tunnel();
        
        //十个人过山洞
        Thread p1 = new Thread(tul,"p1");
        Thread p2 = new Thread(tul,"p2");
        Thread p3 = new Thread(tul,"p3");
        Thread p4 = new Thread(tul,"p4");
        Thread p5 = new Thread(tul,"p5");
        Thread p6 = new Thread(tul,"p6");
        Thread p7 = new Thread(tul,"p7");
        Thread p8 = new Thread(tul,"p8");
        Thread p9 = new Thread(tul,"p9");
        Thread p10 = new Thread(tul,"p10");
        p1.start();
        p2.start();
        p3.start();
        p4.start();
        p5.start();
        p6.start();
        p7.start();
        p8.start();
        p9.start();
        p10.start();
    }
}


class Tunnel implements Runnable{
    private int crossedNum = 0;
    //override
    public void run(){
        Cross();
    } 
    //同步函数--同步锁为this,即main()中创建的tul。 
    public  synchronized void Cross(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        crossedNum++;
        System.out.println(Thread.currentThread().getName()+" have Crossed the tunnel !"+" This is "+crossedNum+"th");
        
    }
}

<console>:

image

posted @ 2015-07-16 18:59  cuiz_book  阅读(2428)  评论(0编辑  收藏  举报