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");
// 你的代码将嵌入这里
Input Description
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
我的想法:
我的代码:
public class Main {
public static void main(String[] args) {
Tunnel tul = new Tunnel();
Thread tom = new Thread(tul, "Tom");
// 你的代码将嵌入这里
Thread peter = new Thread(tul, "Peter");
Thread bob = new Thread(tul, "Bob");
try {
tom.start();
Thread.sleep(1000);
peter.start();
Thread.sleep(1000);
bob.start();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Tunnel implements Runnable {
private static int i = 0;
@Override
public void run() {
i++;
System.out.println(Thread.currentThread().getName()+" have Crossed the tunnel!This is " + i + "th");
}
}