Я изучаю параллелизм и делаю некоторые наивные программы для игры с ExecutorService
и Future
задачами.stop Callable task in ExecutorService
Также я хочу проверить, почему в некоторых случаях 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();
}
}
}
но, к сожалению, мой код никогда не прекращается, и я не могу получить любые значения из моих задач :(
Работы для меня: http://ideone.com/AYmuZD Просьба сравнить импорт с кодом, указанным в предыдущей ссылке. Пробовал с ideone, а также локально с Java 6, ничего су там. – Matthias
Я пробовал это много раз, но только то, что я вижу: Задача началась ... Задание начато ... сервис отключен ... –
Возможно, вы захотите заглянуть в 'jstack', который позволяет стеку трассировки для всех потоков в вашей JVM. Это всегда хороший первый шаг для выяснения того, что происходит в «застрявшем» приложении Java. – yshavit