在ExecutorService中停止Callable任务

时间:2013-11-18 15:43:05

标签: java concurrency executorservice future

我正在学习并发性,并使用ExecutorServiceFuture任务制作了一些天真的程序。

另外,我想检查instanceof在某些情况下为什么不好。

public class Test {

static enum Some {
    FOO;
}

static abstract class Foo {
    public abstract Some getType();
}

static class FooExt extends Foo {
    public Some getType() {
        return Some.FOO;
    }
}

public static void main(String[] args) {

    ExecutorService service = Executors.newFixedThreadPool(2);
    final CountDownLatch start = new CountDownLatch(1);
    Future<Integer> f1 = service.submit(new Callable<Integer>() {
        @Override
        public Integer call() {
            try {
                start.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task started...");
            int a = 0;
            Foo foo = new FooExt();
            while (!Thread.currentThread().isInterrupted()) {
                if (foo instanceof FooExt) {
                    a++;
                }
            }
            System.out.println("Task ended...");
            return a;
        }
    });

    Future<Integer> f2 = service.submit(new Callable<Integer>() {
        @Override
        public Integer call() {
            try {
                start.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task started...");
            int a = 0;
            Foo foo = new FooExt();
            while (!Thread.currentThread().isInterrupted()) {
                if (foo.getType() == Some.FOO) {
                    a++;
                }
            }
            System.out.println("Task ended...");
            return a;
        }
    });
    start.countDown();
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
    }
    service.shutdownNow();
    System.out.println("service is shutdowned...");
    try {
        System.out.println("instanceof: "+f1.get());
        System.out.println("enum: "+f2.get());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

但不幸的是我的代码永远不会终止,我无法从我的任务中获得任何值:(

1 个答案:

答案 0 :(得分:0)

嗨,我执行了你的程序。我得到了以下输出:

Task started...
Task started...
Task ended...
service is shutdowned...
Task ended...
instanceof: 1287184
enum: 1247375

此代码终止。