【发布时间】:2013-12-01 20:09:22
【问题描述】:
我正在学习并发,并编写了一些简单的程序来处理 ExecutorService 和 Future 任务。
我还想检查为什么 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();
}
}
}
但不幸的是,我的代码从未终止,我无法从我的任务中获取任何值:(
【问题讨论】:
-
为我工作:ideone.com/AYmuZD 请将导入与上一个链接中发布的代码进行比较。用 ideone 试过,也用 Java 6 在本地试过,没什么奇怪的。
-
我试了很多次,但我看到的只是:任务启动...任务启动...服务被关闭...
-
您可能想查看
jstack,它可以让您获得 JVM 中所有线程的堆栈跟踪。了解“卡住”的 Java 应用程序中发生了什么总是一个很好的第一步。 -
谢谢,我试试
jstack
标签: java concurrency executorservice future