Comment Forcer le Kill d'un thread
Bonjour,
Je ne trouve pas le moyen de détruire un thread sans utiliser de méthodes deprecated du style Beaucoup de sites conseillent d'utiliser un boolean qui determine l'etat du thread ... par exemple comme ci dessous décrit dans la FAQ Java de developpez.com :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
private boolean stopThread = false;
public void run() {
boolean fin = false;
while( !fin ) {
try {
// traitement
synchronized(this) {
Thead.yield();
// lecture du boolean
fin = this.stopThread;
}
} catch( InterruptedException e ) {
}
}
}
public synchronized void stop() {
this.stopThread = true;
} |
Mais ma problématique est que j'utilise une methode qui dure environ 2 minutes.
J'aimerai pouvoir Forcer la destruction du thread pendant que cette méthode est entrain de s'executer.
Voici le code de ma méthode en question ( C'est une insertion de données en base) :
Code:
1 2 3 4
|
...
stmt.execute("LOAD DATA INFILE 'datainsert.csv' INTO TABLE t_ma_table FIELDS TERMINATED BY ';';");
... |
Quelqu'un pourrait t'il me dire comment forcer le kill d'un thread en execution?
Merci
gérer interruptedException
utilise thread.interrupt() et met un "return" dans le catch (interrupted) sinon tu ignore toutes les interruptions et tu reboucles.
démonstration avec un test unitaire:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
import junit.framework.Assert;
import org.junit.Test;
/**
* <code>InterruptThreadTest</code>
* Demonstration of a way to manage interruptedException.
*
* @author deltree
*/
public class TestInterruptThread implements Runnable {
public boolean catched = true;
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while ( true ) {
try {
synchronized ( this ) {
this.wait( 10000 );
}
}
catch ( InterruptedException e ) {
//never cancel an interrupt.
//see http://www.ibm.com/developerworks/java/library/j-jtp05236.html
System.out.println( "i was interrupted" );
if ( !catched ) {
return;
}
}
}
}
@Test
public void testInterrupt() throws InterruptedException {
TestInterruptThread it;
Thread t = new Thread( it = new TestInterruptThread() );
t.start();
t.interrupt();
Thread.sleep( 10 );
Assert.assertTrue( t.isAlive() );
t.interrupt();
Thread.sleep( 10 );
Assert.assertTrue( t.isAlive() );
t.interrupt();
Thread.sleep( 10 );
Assert.assertTrue( t.isAlive() );
t.interrupt();
Thread.sleep( 10 );
Assert.assertTrue( t.isAlive() );
t.interrupt();
Thread.sleep( 10 );
Assert.assertTrue( t.isAlive() );
//OK we have see that the thread is never interrupted in this way
//Now interrupt it the right way
it.catched = false;
t.interrupt();
Thread.sleep( 10 );
Assert.assertFalse( t.isAlive() );
} |