Estou com dúvida na seguinte questão de threads.
A pergunta é a seguinte:
Given:
public class Starter extends Thread {
private int x = 2;
public static void main(String[] args) throws Exception {
new Starter().makeItSo();
}
public Starter() {
x = 5;
start();
}
public void makeItSo() throws Exception {
join();
x = x - 1;
System.out.println("x = " + x);
}
public void run() {
x *= 2;
}
}
What is the output if the main() method is run?
A. 4
A. 4
B. 5
C. 8
D. 9
E. Compilation fails.
F. An exception is thrown at runtime.
G. It is impossible to determine for certain.
E a resposta que está certa segundo o mock é a D.
Eu não entendi direito esse start() e esse join() não deveria ser assim por exemplo. t.start e t.join().
Mesmo sem a referencia ele cria a thread. Normal isso ?
Testei no Eclipse e ele cria a Thread-0.
Pra chegar no valor 9 ele teria que seguir os seguintes passos.
- A variável x começa valendo 2
- newStarter() - Ao passar pelo contrutor passa a valer 5
- No próprio construtor é iniciada a nova thread
- Como iniciou a nova thread o código run é executado ( x*=2 => x=5*2 => 10 )
- join() - Junto a thread main no final da "Thread-0". Enquanto a "Thread-0" não terminar, o main fica aguardando.
- Quando a "Thread-0" termina x= x-1 que é igual a 9.
É isto que acontece ?
