Bom Dia. Estou precisando de uma ajuda com Threads.
Tenho um projeto que funciona um cronômetro através de uma Thread.
No projeto existe uma variável que tem que iniciar e terminar a Thread. Exemplo:
Se a variável x estiver true inicia o cronômetro através da Theard e o cronômetro aparece num JLabel, agora eu queria que quando a variável x estiver false pare o cronômetro, ouseja termine a Thread. Detalhe, só que não vai executar só uma Thread, ou um cronômetro, as vezes pode executar 10 cronômetos ou mais ao mesmo tempo. Como que eu vou parar um determinado cronômentro"Thread", terei que localizar a Thread que está executando o determinado ´cronômetro e parar a execução.
Tentei mas não consegui.
Por favor me ajude.
Veja meu código.
public class CronometroThread implements Runnable {
private Thread hiloCronometro;
private boolean go,live;
private int segundos;
JLabel label = new JLabel("0 : 0 : 0");
public CronometroThread(JLabel v) {
label = v;
}
@Override
public void run() {
try {
while (isLive()) {
synchronized(this) {
while (!isGo())
wait();
}
Thread.sleep(1000);
segundos++;
actualizarThread();
}
} catch (InterruptedException e) {
}
}
public void createThread() {
hiloCronometro = new Thread(this);
hiloCronometro.start();
}
private void actualizarThread() {
if (isLive() == true) {
int hr= segundos/3600;
int min =(segundos-hr*3600)/60;
int seg = segundos-hr*3600-min*60;
label.setText(""+hr+" : "+min+" : "+seg);
} else {
segundos = 0;
label.setText("0 : 0 : 0");
}
}
public void suspenderThread() {
setGo(false);
}
public synchronized void continuarThread() {
setGo(true);
notify();
}
//********** MÉTODOS SET Y GET DE LAS VARIABLES DE TIPO BOOLEAN e INT ************
/**
* @return the live
*/
public boolean isLive() {
return live;
}
/**
* @param live the live to set
*/
public void setLive(boolean live) {
this.live = live;
}
/**
* @return the go
*/
public boolean isGo() {
return go;
}
/**
* @param go the go to set
*/
public void setGo(boolean go) {
this.go = go;
}
/**
* @return the segundos
*/
public int getSegundos() {
return segundos;
}
/**
* @param segundos the segundos to set
*/
public void setSegundos(int segundos) {
this.segundos = segundos;
System.out.println("Valor de SEgundos:" + this.segundos);
}
}
Iniciando o cronômetro através da Thread
CronometroThread crontheard = new CronometroThread(JLabel);
crontheard.createThread();
crontheard.setLive(true);
crontheard.setGo(true);
Tentando finalizar a Theard
crontheard.setLive(false);
crontheard.setGo(false);
crontheard.suspenderThread();