1

I'm trying to use threads in java in order to convert a List of images into pdf.

I'm actually using a loop to convert execute my convertImage method, but the execution time is too long.

    for (File imageFile : images) {     
            logger.debug("addImageAndText "+imageFile.getAbsolutePath());
            convertImage(document, writer, imageFile);
        }

What is the best way to replace my loop with threads and is there a way make sure that threads execution order is the same of the For loop.

I'm pretty new to using threads in java, I would appreciate links to documentation.

Hossam Oukli
  • 1,296
  • 3
  • 19
  • 42
  • 1
    There's no way to ensure order of thread execution in Java. Of course you can assign priority to them, but still the order is not guaranteed. – Aditya Narayan Dixit Dec 27 '18 at 15:47
  • 2
    Why do you need to keep the order of for loop? If it is required, try to label each file before doing the conversion. And you can take a look at parallel stream in Java 8 in order to process a collection concurrently. – thanh ngo Dec 27 '18 at 15:52
  • Is it not possible to just resort the images to a desired order once they are all processed? I am curious what you are trying to accomplish. Anyway here's your [documentation](https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html) – Stalemate Of Tuning Dec 27 '18 at 16:11
  • Do you need control the threads execution order ? Or just wait for all threads to finish. You can do both by using locks or `wait` - `notify` and [other techniques](https://docs.oracle.com/javase/tutorial/essential/concurrency/). Most probably your best bet would be to use a [Stream](https://stackoverflow.com/a/53923981/3992939). – c0der Dec 27 '18 at 16:47

0 Answers0