[SCJP] Threads e classes anônimas

Estava analisando um código que envolvia Threads e Classes anônimas:

[code]public class TestRunnable implements Runnable {
public static void main(String[] args) {
TestRunnable myRunnnable = new TestRunnable();

	new Thread(myRunnnable){
		public void run() {
			System.out.println("Anonymous Class");
		}
	}.start();
}

public void run() {
	System.out.println("TestRunnable");
}

}[/code]

A saída desse programa é “Anonymous Class”.
Pra mim isso não fez sentido, pois, a classe Thread só irá chamar o método run() caso não haja nenhum argumento do tipo Runnable no seu construtor, mas com a sobrescrita ele acaba sendo chamado…
Alguém sabe porque isso acontece?

Abs.

Não é isso não. E não tem nada a ver com classes anônimas.

Esse é o método run() da classe Thread:

/**
* If this thread was constructed using a separate 
* <code>Runnable</code> run object, then that 
* <code>Runnable</code> object's <code>run</code> method is called; 
* otherwise, this method does nothing and returns. 
* <p>
* Subclasses of <code>Thread</code> should override this method. 
*
* @see     #start()
* @see     #stop()
* @see     #Thread(ThreadGroup, Runnable, String)
*/
public void run() {
   if (target != null) {
      target.run();
   }
}

target é o Runnable que você passou no construtor.

Como você pode ver é o método run() e não o método start() que decide chamar o target. Portanto, se você sobrescrever o método run(), não adianta nada passar um outro runnable no construtor, já que o que vai rodar é o código sobrescrito, e não esse código aí.

Só para confirmar, veja como o método start() não faz qualquer menção ao target:

/**
* Causes this thread to begin execution; the Java Virtual Machine 
* calls the &lt;code&gt;run&lt;/code&gt; method of this thread. 
* <p>
* The result is that two threads are running concurrently: the 
* current thread (which returns from the call to the 
* &lt;code&gt;start&lt;/code&gt; method) and the other thread (which executes its 
* &lt;code&gt;run&lt;/code&gt; method). 
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception  IllegalThreadStateException  if the thread was already
*               started.
* @see        #run()
* @see        #stop()
*/
public synchronized void start() {
   /**
   * This method is not invoked for the main method thread or "system"
   * group threads created/set up by the VM. Any new functionality added 
   * to this method in the future may have to also be added to the VM.
   *
   * A zero status value corresponds to state "NEW".
   */
   if (threadStatus != 0)
      throw new IllegalThreadStateException();
   group.add(this);
   start0();
   if (stopBeforeStart) {
      stop0(throwableFromStop);
   }
}

O que o método start() faz é simplesmente criar uma nova thread inicia-la em this.run(). Que, no caso, é o seu método sobrescrito.

Ah tah entendi, o método run da Thread que chama o método run() do target, legal!
Mas… Porque não tem nada a ver com classes anônimas? Esse código acima não representa uma classe anônima?

Abs.

Só complementando, note que o javadoc do método start diz exatamente isso:

Mas fica implícito que a implementação padrão do método run() é que chama o run() do Runnable.

[quote=gervas-IO]Ah tah entendi, o método run da Thread que chama o método run() do target, legal!
Mas… Porque não tem nada a ver com classes anônimas? Esse código acima não representa uma classe anônima?[/quote]

Sim, só estava falando que o problema não tem nada a ver com o fato da sua classe ser ou não anônima. Se você tivesse feito uma outra classe “MinhaThread” e sobrescrito o run() dela de maneira não anônima, o resultado seria exatamente o mesmo.

Eis um exemplo:

[code]class MinhaThread extends Thread {
public MinhaThread(Runnable r) {
super®;
}

public void run() {
System.out.println(“Non-Anonymous Class”);
}
}

public class TestRunnable implements Runnable {
public static void main(String[] args) {
TestRunnable myRunnnable = new TestRunnable();
new MinhaThread(myRunnnable).start();
}

public void run() {
	System.out.println("TestRunnable");
}

}[/code]

É uma versão não-anônima do que seu código já faz. Como vc pode ver, a saída é “Non-Anonymous Class” e o Runnable também foi ignorado.

Ok. Obrigado!