过山洞 Java

题目描述

编写多线程应用程序,模拟三个人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");
// 你的代码将嵌入这里

输出描述

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

 

 

Thread peter = new Thread(tul,"Peter");
		Thread bob = new Thread(tul,"Bob");
	
		tom.start();
		peter.start();
		bob.start();
	}
}
class Tunnel implements Runnable
{
	
	public void run()
	{
		for(int i = 1;i<=3;i++)
		{
			if(i == 1&&Thread.currentThread().getName().equals("Tom"))
			{
				System.out.println("Tom"+" have Crossed the tunnel!This is "+i+"th");
				i++;
			}
		    if(i == 2&&Thread.currentThread().getName().equals("Peter"))
			{
				System.out.println("Peter"+" have Crossed the tunnel!This is "+i+"th");
				i++;
			}
			if(i == 3&&Thread.currentThread().getName().equals("Bob"))
			{
				System.out.println("Bob have Crossed the tunnel!This is "+i+"th");
				i++;
			}
		}
			
	}
}

 

posted @ 2019-01-12 16:06  RomanticChopin  阅读(159)  评论(0编辑  收藏  举报
-->
Live2D