difícil (certificacao)

12 respostas
maxguzenski

essa eu considero difícil

public class TestClass implements Runnable {
  int x = 0, y = 0; 

  public void run()  {
    while(true)  {
      x++; y++;
      System.out.println(" x = "+x+" , y = "+y);
    }
  }

  public static void main(String[] args)  {
    TestClass tc = new TestClass();
    new Thread(tc).start();
    new Thread(tc).start();
  }
}
 

Select 1 correct option.

a) It will throw exception at run time as two thread cannot be created from the same object.

b) It will keep on printing values which show x and y always as equal and increasing by 1 at each line.
 
c) It will keep on printing values which show x and y always as different.
 
d) Nothing can be said about the sequence of values.
 
e) It will keep on printing values which show x and y always as equal but may increase more than 1 at each line.

12 Respostas

R

eu ficaria entre as alternativas a) e b)…

to certo??

urubatan

eu ficaria entre A e D :slight_smile:
se rodar, fica completamente impossivel de dizer o que vai acontecer com os numeros :slight_smile:

smota

eu chuto a D.

Acho que roda (por isso não a A) pois é possível se você fizer corretamente sincronização.

e ai?

maxguzenski

isso.
a resposta correta é D

smota

“maxguzenski”:
isso.
a resposta correta é D

bingo! :smiley:

Agora que esta confirmado … alguem sabe explicar porque ao rodar mesmo ele se comporta como a resposta B? :roll:

Teoricamente a D está correta, mas rodei umas 3 vezes e o resultado impresso sempre foi sequencial e correto.

Vai entender …

[]s

maxguzenski

pq sao thread, e nao da para saber quando uma ou a outra vai ganhar o processador !!!

exemplo:

X=0, Y=0;

THREAD 1 ganha o processador, e executa X++; Y++; logo apos ocorre uma interrupção. então:
THREAD 2 ganha o processador, e executa X++, Y++; logo apos ocorre uma interrupção. então:
THREAD 1 volta a executar e mostra X e Y na tela, so que dessa vez ao inves de incrementar 1, X e Y estaram valendo +2 …

se você tivesse executado com varios outros processos na fila, ou num ombiente multi-processado, ou em N outras cituações diferentes, os resultados poderiam variar.

entendeu?

smota

Isso eu sei, mas também pode ocorrer:

THREAD 1: x++; y++;

INTERRUPÇÃO

THREAD 2: x++; y++;

INTERRUPÇÃO

" x = 2 , y = 2 "

mas não ocorre :? (pelo menos não na minha amostragem)

entre o x++ e y++ também poderia ocorrer uma interrupção, ai os valores deixariam de ter paridade … tb nao ocorre :cry:

ozielneto

Resposta D, pois O Scheduler da JVM não se importa se uma deve ir antes ou depois, ou vice-versa…

Para garantir a ordem de execução, os incrementos do atributos deveriam estar sincronizados…

[]'s

L

Prova que o Oziel está certo.

Deem uma olhada na saída das últimas linhas

Esta é a saída do seguinte código:

public class TestClass implements Runnable { 
  int x = 0, y = 0; 

  public void run()  { 
    while(true)  { 
      x++; y++; 
      System.out.println(" x = "+x+" , y = "+y+ " thread: " + 

Thread.currentThread()); 
    } 
  } 

  public static void main(String[] args)  { 
    TestClass tc = new TestClass(); 
    Thread t1 = new Thread(tc);
    
    t1.setPriority(Thread.MIN_PRIORITY);
    
    try{
       t1.sleep(5);
    }catch(InterruptedException e) {

	e.printStackTrace();
    }
    t1.start(); 

    Thread t2 = new Thread(tc);
    t2.setPriority(Thread.MAX_PRIORITY);	
    t2.start(); 


  } 
}

Saída:

x = 9273 , y = 10475 thread: Thread[Thread-2,10,main]
x = 9274 , y = 10476 thread: Thread[Thread-2,10,main]
x = 9275 , y = 10477 thread: Thread[Thread-2,10,main]
x = 9276 , y = 10478 thread: Thread[Thread-2,10,main]
x = 9277 , y = 10479 thread: Thread[Thread-2,10,main]
x = 9278 , y = 10480 thread: Thread[Thread-2,10,main]
x = 9279 , y = 10481 thread: Thread[Thread-2,10,main]
x = 9280 , y = 10482 thread: Thread[Thread-2,10,main]
x = 9281 , y = 10483 thread: Thread[Thread-2,10,main]
x = 9282 , y = 10484 thread: Thread[Thread-2,10,main]
x = 9283 , y = 10485 thread: Thread[Thread-2,10,main]
x = 9284 , y = 10486 thread: Thread[Thread-2,10,main]
x = 9285 , y = 10487 thread: Thread[Thread-2,10,main]
x = 9286 , y = 10488 thread: Thread[Thread-2,10,main]
x = 9287 , y = 10489 thread: Thread[Thread-2,10,main]
x = 9288 , y = 10490 thread: Thread[Thread-2,10,main]
x = 9289 , y = 10491 thread: Thread[Thread-2,10,main]
x = 9290 , y = 10492 thread: Thread[Thread-2,10,main]
x = 9291 , y = 10493 thread: Thread[Thread-2,10,main]
x = 9292 , y = 10494 thread: Thread[Thread-2,10,main]
x = 9293 , y = 10495 thread: Thread[Thread-2,10,main]
x = 9294 , y = 10496 thread: Thread[Thread-2,10,main]
x = 9295 , y = 10497 thread: Thread[Thread-2,10,main]
x = 9296 , y = 10498 thread: Thread[Thread-2,10,main]
x = 9297 , y = 10499 thread: Thread[Thread-2,10,main]
x = 9298 , y = 10500 thread: Thread[Thread-2,10,main]
x = 9299 , y = 10501 thread: Thread[Thread-2,10,main]
x = 9300 , y = 10502 thread: Thread[Thread-2,10,main]
x = 9301 , y = 10503 thread: Thread[Thread-2,10,main]
x = 9302 , y = 10504 thread: Thread[Thread-2,10,main]
x = 9303 , y = 10505 thread: Thread[Thread-2,10,main]
x = 9304 , y = 10506 thread: Thread[Thread-2,10,main]
x = 9305 , y = 10507 thread: Thread[Thread-2,10,main]
x = 9306 , y = 10508 thread: Thread[Thread-2,10,main]
x = 9307 , y = 10509 thread: Thread[Thread-2,10,main]
x = 9308 , y = 10510 thread: Thread[Thread-2,10,main]
x = 9309 , y = 10511 thread: Thread[Thread-2,10,main]
x = 9310 , y = 10512 thread: Thread[Thread-2,10,main]
x = 9311 , y = 10513 thread: Thread[Thread-2,10,main]
x = 9312 , y = 10514 thread: Thread[Thread-2,10,main]
x = 9313 , y = 10515 thread: Thread[Thread-2,10,main]
x = 9314 , y = 10516 thread: Thread[Thread-2,10,main]
x = 9315 , y = 10517 thread: Thread[Thread-2,10,main]
x = 9316 , y = 10518 thread: Thread[Thread-2,10,main]
x = 9317 , y = 10519 thread: Thread[Thread-2,10,main]

Paulo_Silveira

Esse Leandro deve ter feito curso com algum instrutor muito bom… :slight_smile:

smota

ehehe falaram falaram e não disseram nada :shock:

Já tinhamos chegado a conclusão que a resposta certa era a D e também o porque … a dúvida que ficou é “Existe uma explicação para o código original ter um comportamento tão certinho mesmo sem sincronização ou controle por prioridade das threads?” Eu acho que não :lol!: …

[]s

L

Colega,

O código que eu enviei simula uma situação em que seu processador estaria ocupado demais com alguma outra coisa e que por isso as threads não seriam escalonadas da forma correta.

Só escrevi o programa assim pq eu não queria ficar ripando um DVD e codificando para DIVX ao mesmo tempo que rodo o exemplo das Threads…

Como esse laço infinito leva o uso de processador lá em cima, uma Thread vai ter prioridade sobre outra, mas o mesmo ocorre no explemplo original.

Coloquei a mensagem somente para ilustrar e esclarecer para quem desejar…

Quanto a isso, tente o esquema do DIVX, vc vai ver que funciona…

Um abraço,

Criado 11 de junho de 2003
Ultima resposta 12 de jun. de 2003
Respostas 12
Participantes 7