Tworzenie wątków wywoływalnych jako demonów

Jak mogę utworzyć wątek Callable jako wątek demona?

Oto, co próbuję. Próbuję wykonać zestaw wątków, z których jeden nie jest kompletny i przechodzi w nieskończoną pętlę. To, co robi, to główny wątek programu, nie kończy się, mimo że wszystkie instrukcje kodu są wykonywane. Główny wątek przechodzi następnie w tryb zawieszenia.

Oto fragment kodu dla tego samego.

<code>public class MyThread implements Callable<String> {

    private int value;

    public MyThread(int value) {
        this.value = value;
    }

    @Override
    public String call() throws Exception {

        //Thread.currentThread().setDaemon(true);

        System.out.println("Executing - " + value);

        if (value == 4) {
            for (; ; );
        }

        return value + "";
    }
}
</code>

Główny program

<code>public class ExecutorMain {

    public static String testing() {    
        ExecutorService executor = null;
        List<Future<String>> result = null;
        String parsedValue = null;
        try {
            executor = Executors.newSingleThreadExecutor();

            List<MyThread> threads = new ArrayList<MyThread>();

            for (int i = 1; i < 10; i++) {
                MyThread obj = new MyThread(i);
                threads.add(obj);
            }

            result = executor.invokeAll(threads, Long.valueOf("4000"), TimeUnit.MILLISECONDS);
            //result = executor.invokeAll(threads);

            for (Future<String> f : result) {
                try {
                    parsedValue = f.get();
                    System.out.println("Return Value - " + parsedValue);
                } catch (CancellationException e) {
                    System.out.println("Cancelled");
                    parsedValue = "";
                    f.cancel(true);
                }
            }

            executor.shutdownNow();
        } catch (Exception e) {
            System.out.println("Exception while running threads");
            e.printStackTrace();
        } finally {
            List executedThreads = executor.shutdownNow();

            System.out.println(executedThreads);

            for (Object o : executedThreads) {
                System.out.println(o.getClass());
            }
        }
        System.out.println("Exiting....");
        //System.exit(1);

        return "";
    }

    public static void main(String[] args) {
        testing();
    }
}
</code>

Co zrozumiałem z mojego wcześniejszego pytania oZwisające wątki w Javie jest to, że muszę tworzyć moje wątki jako wątki demona.

questionAnswers(4)

yourAnswerToTheQuestion