Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Threading Tutorial Type Question

I am fairly naive when it comes to the world of Java Threading and Concurrency. I am currently trying to learn. I made a simple example to try to figure out how concurrency works.

Here is my code:

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

public class ThreadedService {

    private ExecutorService exec;

    /**
     * @param delegate
     * @param poolSize
     */
    public ThreadedService(int poolSize) {
        if (poolSize < 1) {
            this.exec = Executors.newCachedThreadPool();
        } else {
            this.exec = Executors.newFixedThreadPool(poolSize);
        }
    }

    public void add(final String str) {
        exec.execute(new Runnable() {
            public void run() {
                System.out.println(str);
            }

        });

    }

    public static void main(String args[]) {
        ThreadedService t = new ThreadedService(25);
        for (int i = 0; i < 100; i++) {
            t.add("ADD: " + i);
        }
    }

}

What do I need to do to make the code print out the numbers 0-99 in sequential order?

like image 965
mainstringargs Avatar asked Jan 26 '26 22:01

mainstringargs


1 Answers

Thread pools are usually used for operations which do not need synchronization or are highly parallel.

Printing the numbers 0-99 sequentially is not a concurrent problem and requires threads to be synchronized to avoid printing out of order.

I recommend taking a look at the Java concurrency lesson to get an idea of concurrency in Java.

like image 105
Ben S Avatar answered Jan 29 '26 12:01

Ben S