Sto scrivendo un'applicazione che genera più attività simultanee. Sto usando un pool di thread per implementarlo.come interrompere un thread in un threadpool
Può succedere che si verifichi un evento che rende non validi i calcoli eseguiti nelle attività. In tal caso, vorrei interrompere le attività attualmente in esecuzione e avviarne di nuove.
Il mio problema: come posso interrompere le attività attualmente in esecuzione? La soluzione che ho implementato è quella di memorizzare un riferimento al thread dell'attività e chiamare interrupt()
su questo thread. Nel codice dimostrativo:
public class Task implements Runnable {
private String name;
private Thread runThread;
public Task(String name) {
super();
this.name = name;
}
@Override
public void run() {
runThread = Thread.currentThread();
System.out.println("Starting thread " + name);
while (true) {
try {
Thread.sleep(4000);
System.out.println("Hello from thread " + name);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
}
}
public void stop() {
runThread.interrupt();
}
public String getName() {
return name;
}
}
E il metodo principale è:
public static void main(String args[]) {
executorService = Executors.newFixedThreadPool(2);
Task t1 = new Task("Task1");
Task t2 = new Task("Task2");
executorService.execute(t1);
executorService.execute(t2);
executorService.execute(new Task("Task3"));
executorService.execute(new Task("Task4"));
try {
Thread.sleep(12000);
t1.stop();
System.err.println("Stopped thread " + t1.getName());
Thread.sleep(8000);
t2.stop();
System.err.println("Stopped thread " + t2.getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Si tratta di una buona soluzione, o c'è un modo migliore per fermare un thread in esecuzione in un pool di thread?
Estrarre la spina;) – sje397