Terminar un thread sin el método stop()

3324 vistas

Veamos el esqueleto estándar de un thread. Este esqueleto permite parar un thread de forma sencilla sin usar el método 'deprecated' stop().



java
  1. /** Este booleano se usará para señalar al proceso si tiene que continuar o parar */
  2. private boolean stopThread = false;
  3.  
  4. public void run() {
  5.         boolean fin = false;
  6.         while( !fin ) {
  7.                 try {
  8.                         // proceso
  9.                         synchronized(this) {
  10.                                 Thead.yield();
  11.                                 // lectura del booleano
  12.                                 fin = this.stopThread;
  13.                         }
  14.                 } catch( InterruptedException e ) {
  15.                 }
  16.         }
  17. }
  18.  
  19. public synchronized void stop() {
  20.         this.stopThread = true;
  21. }



Otro posible esqueleto:
La anterior solución se adapta a los thread que efectuen regularmente el mismo proceso. Si el proceso es muy largo, puede ser necesario testear la consulta de final durante el transcurso del proceso. Lo más sencillo es levantar una excepción durante este proceso:



java
  1. private boolean stopThread = false;
  2.  
  3. public synchronized void testFin() throws InterruptedException {
  4.         if( stopThread ) {
  5.                 throw new InterruptedException();
  6.         }
  7. }
  8.  
  9. public void run() {
  10.         try {
  11.                 // proceso con una llamada regular a testFin();
  12.         } catch( InterruptedException e ) {
  13.         }
  14. }
  15.  
  16. public synchronized void stop() {
  17.         this.stopThread = true;
  18. }



Atención: las llamadas al método testFin() tienen que hacerse únicamente cuando todos los objetos estén en un estado coherente.