I have the following code snippet. Can someone explain the following question to me?
In main
when I create the two threads, I go to the Boat
constructor and notice that it sleeps a second. Why is it main
that assumes this sleep
in its time and why is not each thread individually?
public class Boat extends Thread{
private Dock dock;
private long initialTime;
public Boat(String name, Dock dock, long initialTime) throws InterruptedException{
setName(name);
this.initialTime = initialTime;
this.dock = dock;
sleep(1000);
}
@Override
public void run(){
dock.enter();
try{
dock.exit();
sleep(1000);
System.out.println(getName() + "-" + (System.currentTimeMillis()-initialTime)/1000 + "s");
}catch(InterruptedException e){
}
}
public static void main(String[] args) throws InterruptedException{
long sTime = System.currentTimeMillis();
Dock d = new Dock();
Boat t1 = new Boat("b1", d, sTime);
Boat t2 = new Boat("b2", d, sTime);
System.out.println("Start!");
t1.start();
sleep(1000);
t1.interrupt();
t2.start();
sleep(1000);
d.exit();
t2.join();
sleep(1000);
System.out.println("Main - Finished " + (System.currentTimeMillis()-sTime)/1000+"s");
}
}