Java Threading Tutorial Type Question

I am pretty naive when it comes to the world of Thread Threading and Concurrency. I'm 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 so that the code prints the numbers 0-99 in sequential order?

+3
source share
4 answers

Thread pools are typically used for operations that do not need synchronization or high parallel .

0-99 , .

Java concurrency , concurrency Java.

+7

- ThreadPool 1. , .

, :

this.exec = Executors.newSingleThreadExecutor();

, . , , Threads .

, - , , GUI, , .

+3

- .

. . add. . , , , .

+3

. , , .

, :

public void add(final String str) {
    System.out.println(str);
}

( , ), .

0

Source: https://habr.com/ru/post/1704085/


All Articles