我正在学习并发性,并制作了一些简单的程序来处理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();
}
}
}
但不幸的是,我的代码从未终止,我无法从任务中获得任何值:(
嗨,我已经执行了你的程序。我得到了以下输出:
Task started...
Task started...
Task ended...
service is shutdowned...
Task ended...
instanceof: 1287184
enum: 1247375
此代码终止。