(OJ)Java多线程-过山洞

过山洞

Problem Description

编写多线程应用程序,模拟三个人Tom,Peter,Bob过山洞:
1、这个山洞每次只能通过一个人,每个人通过山洞的时间为1秒
2、过山洞次序为:Tom,Peter,Bob


将下列代码补充完整:

public class Main{
    public static void main(String[] args) {
        Tunnel tul = new Tunnel();
        Thread tom = new Thread(tul,"Tom");
// 你的代码将嵌入这里

Output Description

Tom have Crossed the tunnel!This is 1th
Peter have Crossed the tunnel!This is 2th
Bob have Crossed the tunnel!This is 3th

解题代码

		// 此题为代码补全题
		// 创建线程peter 并设置线程名为peter
		Thread peter = new Thread(tul, "Peter");
		// 创建线程 bob 并设置线程名为Bob
        Thread bob = new Thread(tul, "Bob");
		// 线程休眠可能发生异常 这里直接try catch 因为上面mian方法写死了
        try {
    
    
            // 启动tom线程
            tom.start();
            // 主线程休眠1s 每个人通过山洞的时间为1秒
            Thread.sleep(1000);
            // 启动peter线程
            peter.start();
            // 主线程休眠1s
            Thread.sleep(1000);
            // 启动bob线程
            bob.start();
            // 主线程休眠1s
            Thread.sleep(1000);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

// Tunnel类 实现了Runable接口 创建线程除了实现Runnable接口 还可以继承Thread类
class Tunnel implements Runnable{
    
    
    // 变量i用于记录序号 
    // 由于创建使用的Tunnel实例时同一个 这个变量相当于是共享的
    private int i = 0;
    
    // 实现run方法 线程在启动之后会执行run方法
    @Override
    public void run() {
    
    
        // 序号加1
        i++;
        // 打印信息
        System.out.println(Thread.currentThread().getName()+" have Crossed the tunnel!This is " + i + "th");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112723701