Is it possible to interrupt a specific thread of the ExecutorService?

If I have a ExecutorServiceRunnable tasks I'm uploading to, can I select it and abort it?
I know that I can cancel the Future returned (also mentioned here: as-to-interrupt-executors-thread ), but how can I raise it InterruptedException. Canceling does not seem to do this (an event, although one needs to look at the sources, perhaps the OSX implementation is different). At least this snippet does not print β€œthis!”. Maybe I'm misinterpreting something, and this is not an ordinary version that gets an exception?

public class ITTest {
static class Sth {
    public void useless() throws InterruptedException {
            Thread.sleep(3000);
    }
}

static class Runner implements Runnable {
    Sth f;
    public Runner(Sth f) {
        super();
        this.f = f;
    }
    @Override
    public void run() {
        try {
            f.useless();
        } catch (InterruptedException e) {
            System.out.println("it!");
        }
    }
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
    ExecutorService es = Executors.newCachedThreadPool();
    Sth f = new Sth();
    Future<?> lo = es.submit(new Runner(f));
    lo.cancel(true); 
    es.shutdown();
}

}

+5
source share
1 answer

- Future. , InterruptedException.

, - , . , (). , .

sleep(), wait() InterruptedException. , , :

if (Thread.currentThread().isInterrupted()) {

, , InterruptedException:

try {
   Thread.sleep(1000);
} catch (InterruptedException e) {
   // this is a good pattern otherwise the interrupt bit is cleared by the catch
   Thread.currentThread().interrupt();
   ...
}

, lo.cancel(true). , , .

+10

All Articles