Tenho uma Thread que implementa um contador simples…
Chamo essa Thread a partir de uma classe Main…
Através de outra classe Main retorno o valor do cont atual dentro da Thread…
É possível?
public class TesteThread extends Thread {
private Integer cont = 0;
public Integer getCont() {
return this.cont;
}
public void run() {
while(true) {
cont++;
System.out.println(cont);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TesteThreadMain {
private static TesteThread thread = new TesteThread();
public static TesteThread getTesteThread() {
return thread;
}
public static void main(String[] args) {
thread.start();
System.out.println("t1 id: "+thread.getId());
System.out.println("t1 nome: "+thread.getName());
}
}
public class TesteThreadMain2 {
public static void main(String[] args) {
TesteThread t = TesteThreadMain.getTesteThread();
System.out.println("t id: "+t.getId());
System.out.println("t nome: "+t.getName());
System.out.println("cont: "+t.getCont());
}
}
Quando eu rodo o Main2 o interessante que ele retorna o ID e Nome corresponde à thread, exceto o valor do cont…