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
题解代码
要想让过山洞次序为:Tom,Peter,Bob
那么就需要使用join 来进行插队处理
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");
tom.start();
try {
tom.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Peter.start();
try {
tom.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Bob.start();
try {
tom.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
class Tunnel implements Runnable{
static int num=1;
@Override
public void run()
{
synchronized (Thread.class)
{
try {
Thread.sleep(1000);//过山洞的时间
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Thread tmp = Thread.currentThread();
System.out.println(tmp.getName()+" have Crossed the tunnel!This is "+num+"th");
num++;
}
}
}