Assume the following method is properly synchronized and called from thread A on an object B:
wait(2000);
After calling this method, when will the thread A become a candidate to get another turn at the CPU?
A. After object B is notified, or after two seconds.
B. After the lock on B is released, or after two seconds.
C. Two seconds after object B is notified.
D. Two seconds after lock B is released.
resposta: A
Eu não entendi porque A e também não entendi a justificativa de resposta dada pelo livro da K. Sierra.
Alguém pode elucidar essa questão pra mim? desde já agradeço muito mesmo
class A{
public static void main (String []args){
B b = new B();
b.start();
}
synchronized (b){ // o thread obtém um bloqueio em 'b'
try{
b.wait(2000);
/* o thread libera o bloqueio e espera notify
somente por 2 segundos, dai o thread readiquire o bloqueio
*/
}catch (InterruptedException ie){
ie;
}
}
}
class B extends Thread{
public void run (){
synchronized (this){
try{
b.notify(): // notificará a qualquer outra Thread que estiver aguardando b
}catch (InterruptedException ie){
ie;
}
}
}
}[/code]
Acho que isso explica a questão tipo, a Thread A só poderá bloquear B após 2 segundos ( wait(2000); ) ou quando o método notify(); for chamado;
Caso não fosse passado como parâmetro os 2000 milesegundos, A só poderia bloquear b após o notify() (ou um notifyAll(); )
Letra B não é válida porque não podemos garantir que A bloqueará B depois do bloco B ser liberado, já que não temos como saber que B foi liberado sem o notify().
Muito Obrigado William Alves, vc respondeu minha dúvida! O termo “on a object B” me confundiu, pensei que o wait() estava sendo acionado pela thread A.