public class TwoThreads {
private static Object resource = new Object();
private static void delay(long n) {
try {
Thread.sleep(n);
} catch (Exception e) {
System.out.print("Error " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.print("StartMain ");
new Thread1().start();
delay(1000);
Thread t2 = new Thread2();
t2.start();
delay(1000);
t2.interrupt();
delay(1000);
System.out.print("EndMain ");
}
static class Thread1 extends Thread {
public void run() {
synchronized (resource) {
System.out.print("Startl ");
delay(6000);
System.out.print("End1 ");
}
}
}
static class Thread2 extends Thread {
public void run() {
synchronized (resource) {
System.out.print("Start2 ");
delay(2000);
System.out.print("End2 ");
}
}
}
}
/*Assume that sleep(n) executes in exactly m milliseconds, and all other
code executes in an insignificant amount of time. What is the output if
the main() method is run?
A. Compilation fails.
B. Deadlock occurs.
C. StartMain Start1 Error EndMain End1
D. StartMain Start1 EndMain End1 Start2 End2
E. StartMain Start1 Error Start2 EndMain End2 End1
F. StartMain Start1 Start2 Error End2 EndMain End1
G. StartMain Start1 EndMain End1 Start2 Error End2
Answer: G*/
Fiquei bem confuso com esta pergunta, compilei e debuggei o código e cheguei a seguinte conclusão:
o método main inicia e printa StartMain e dispara o Thread1, que printa Start1 e entra em sleep durante 6 segundos e obtém o lock de resource, concorrentemente main entra em sleep por 1 segundo, depois disto starta o Thread2, que não inicia imediatamente pois o Thread1 possuí o lock em resource, o método main entra em sleep por um segundo novamente, depois chama interrupt() no Thread2, este método não para o Thread, apenas faz com que o sleep se chamado lance uma InterruptedException, main entra em sleep novamente, por 1 segundo e finalmente printa EndMain, depois disto o Thread1 finaliza printando End1, assim o lock em resource é liberado e Thread2 pode executar, ele printa Start2, tentar chamar sleep nele mesmo através do método delay, isto causa o lançamento de uma interrupted exception, printando Error, e depois finaliza printando End2.
Estou certo?? Tem alguma coisa para acrescentar??
[]'s e obrigado!