0

I have made a ThreadPool in Java. I use it in the following way.

public Image calculateObject() {
    Image img;

    Task task = new Task() {
        @Override
        protected Object call() throws Exception {
            //Calculate the Image.
        }
    }
    threadPool.addTask(task);
    //Wait for task completion.
    return img;
}

Obviously I want to wait until the ThreadPool has manged to complete the task and create the Object before I return from the function. How do I do this, should I implement some sort of wait function in my ThreadPool (How would I go about doing this?)? Have I misunderstood the point of ThreadPools completely and am being stupid?

To clarify, the primary point of my ThreadPool is to make ProgressBars for all Tasks that arrive but also to make sure that important Tasks are completed first.

EDIT: So as HoverCraftFullOfEels pointed out my question is in fact quite dumb. I will try to clarify the problem further. So I want to make a function that will start a Thread that will calculate an Image and return this when done. This creation of the image can take as long as 10 mins and I want to be able to create several at a time but with slightly varying parameters. I also do not want the GUI to lock up when this is happening. When this function completes I want to return the completed Image so it can be saved.

Is it a good idea to make this function in to a Task instead and each time I want to make an Image I run the task? How would I then get this Image from the ThreadPool?

Ivar Eriksson
  • 863
  • 1
  • 15
  • 30
  • Your "obviously" statement suggests that you're confused as to how threading works and why or when to use threading. If you want the method to wait, then you shouldn't be using a thread at all. If you want to use threading, then the method **can't** wait. Period. You'll want to use a notification of some sort such as a call-back mechanism. The Java Concurrency library has call back mechanisms that you may wish to explore. – Hovercraft Full Of Eels Jul 06 '18 at 23:11
  • @HovercraftFullOfEels this is a very good point. I will try to clarify my problem further. – Ivar Eriksson Jul 06 '18 at 23:12
  • @HovercraftFullOfEels would you be so kind as to check out my **Edit**? – Ivar Eriksson Jul 06 '18 at 23:23
  • 1
    The page that @HovercraftFullOfEels linked to talks about the `Future` which is returned when you submit your `Task` to the thread-pool. If you define your `Task` as a `Callable` then the future becomes a `Future` and you can call `future.get(0, TimeUnit.MILLISECONDS)` which will return the `Image` or throw a timeout or other exception. That's how you can return values from your threads. – Gray Jul 06 '18 at 23:55

0 Answers0