I need to return something from a thread

dotMatthew :

I need to create more threads so one of my friends gave me some code for an "ThreadBuilder" but i can't return from a thread. I need now some help to do this. Some piece of code would also be great.

I have tried tried it with an one element final array and with Atomic Reference but it didnt work as expected.

package net.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class ThreadBuilder {

    private static String API_QUEUE = "API QUEUE";
    private static int threads = 0;

    private static final ExecutorService queue;

    static {
        ThreadFactory threadBuilder = r -> {
            Thread thread = new Thread(r, ThreadBuilder.API_QUEUE + ++ThreadBuilder.threads);
            thread.setDaemon(true);
            return thread;
        };
        queue = Executors.newCachedThreadPool(threadBuilder);
    }

    public static void run(Runnable runnable) {
        queue.execute(runnable);
    }

    public static ExecutorService getQueue() {
        return queue;
    }

}
Andy Turner :

Use Callable, and return the result of the queue.submit:

public static <T> Future<T> run(Callable<T> callable) {
    return queue.submit(callable);
}

When the Future has completed, you can get the result using Future.get.


I would also point out that your ThreadBuilder class is worse than just using an ExecutorService directly. For example, you can't shut your executor down, await termination etc. Plus, you are introducing a static binding to that class, which makes things harder to isolate, test etc.

It would be better simply to have a static factory method to create the ExecutorService, and then interact with the ExecutorService directly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322595&siteId=1