public class StaticSync
{
public static final Object s_lock = new Object();
public static int s_counter=0;
public static void main(String... args){
new StaticSync().go();
}
public void go(){
for(int iCounter=0; iCounter<50; iCounter++){
Thread thread = new Thread(new Incrementer(new StaticSync()));
thread.start();
}
}
}
class Incrementer implements Runnable
{
StaticSync m_staticSync=null;
public Incrementer(StaticSync staticSync_INP){
m_staticSync = staticSync_INP;
}
public void run(){
synchronized (m_staticSync.s_lock){
m_staticSync.s_counter++;
System.out.println(m_staticSync.s_counter);
}
}
}
A minha dúvida está na linha 13. Nela, um novo objeto Thread é criado. Mas, logo após esse objeto chamar o start(), assim que ele atingir a linha 15, ele não vai ser marcado para a coleta de lixo? Se ele é marcado para a coleta de lixo, então porque o código continua rodando normalmente?
Eu fiz outro teste aqui também. Coloquei um thread = null; logo abaixo do thread.start();, ou seja:
.
.
.
Thread thread = new Thread(new Incrementer(new StaticSync()));
thread.start();
thread = null;
}
Mesmo assim rodou normalmente :shock: Por que isso acontece?