简体   繁体   中英

I need to return something from a thread

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;
    }

}

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.

Another solution that I can think of is creating a class to hold the result of the computation or whatever you are performing on a different thread, then pass an instance of that class as a parameter to the Runnable itself (kind of like a has-a relation). Then inside the run() method of the Runnable , when the result is obtained, then pass the result on to the result storing object.

Basically, it's the Observer Design Pattern .

This is a actually a bad solution as you have to keep checking whether the result storing object has been updated or not and this is fundamentally bad for design. The only reason why I am suggesting this answer is that you do not know about Callable and I suggest you learn and then refer to @AndyTurner's answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM