Если вы отправите один исполняемый файл в службу-исполнитель с несколькими потоками, будут ли несколько потоков выполнять этот работающий? - PullRequest
0 голосов
/ 07 марта 2019

Мне трудно понять, как работает ExecutorService в Java 8. Я пытался понять часть кода на этом сайте: https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/

Особенно в конце, где он проверяет время выполнения разных карт. Это код:

public class CrunchifyConcurrentHashMapVsSynchronizedMap {

public final static int THREAD_POOL_SIZE = 5;

public static Map<String, Integer> crunchifyHashTableObject = null;
public static Map<String, Integer> crunchifySynchronizedMapObject = null;
public static Map<String, Integer> crunchifyConcurrentHashMapObject = null;

public static void main(String[] args) throws InterruptedException {

    // Test with Hashtable Object
    crunchifyHashTableObject = new Hashtable<String, Integer>();
    crunchifyPerformTest(crunchifyHashTableObject);

    // Test with synchronizedMap Object
    crunchifySynchronizedMapObject = Collections.synchronizedMap(new HashMap<String, Integer>());
    crunchifyPerformTest(crunchifySynchronizedMapObject);

    // Test with ConcurrentHashMap Object
    crunchifyConcurrentHashMapObject = new ConcurrentHashMap<String, Integer>();
    crunchifyPerformTest(crunchifyConcurrentHashMapObject);

}

public static void crunchifyPerformTest(final Map<String, Integer> crunchifyThreads) throws InterruptedException {

    System.out.println("Test started for: " + crunchifyThreads.getClass());
    long averageTime = 0;
    for (int i = 0; i < 5; i++) {

        long startTime = System.nanoTime();
        ExecutorService crunchifyExServer = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        for (int j = 0; j < THREAD_POOL_SIZE; j++) {
            crunchifyExServer.execute(new Runnable() {
                @SuppressWarnings("unused")
                @Override
                public void run() {

                    for (int i = 0; i < 500000; i++) {
                        Integer crunchifyRandomNumber = (int) Math.ceil(Math.random() * 550000);

                        // Retrieve value. We are not using it anywhere
                        Integer crunchifyValue = crunchifyThreads.get(String.valueOf(crunchifyRandomNumber));

                        // Put value
                        crunchifyThreads.put(String.valueOf(crunchifyRandomNumber), crunchifyRandomNumber);
                    }
                }
            });
        }

        // Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation
        // has no additional effect if already shut down.
        // This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.
        crunchifyExServer.shutdown();

        // Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is
        // interrupted, whichever happens first.
        crunchifyExServer.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

        long entTime = System.nanoTime();
        long totalTime = (entTime - startTime) / 1000000L;
        averageTime += totalTime;
        System.out.println("500K entried added/retrieved in " + totalTime + " ms");
    }
    System.out.println("For " + crunchifyThreads.getClass() + " the average time is " + averageTime / 5 + " ms\n");
}

}

Итак, в классе crunchifyPerformTest он запускает ExecutorService с 5 потоками, а затем каждый раз отправляет 5 различных runnables с 500 000 операций чтения и записи в hashmap? Будет ли у службы executor автоматически 5 потоков, выполняющих каждый работающий?

1 Ответ

1 голос
/ 07 марта 2019

Нет.Каждый Runnable выполняется ровно в одном потоке.Это означает, что все Runnable s будут выполняться параллельно, поскольку число Runnable s соответствует количеству доступных потоков.

Вы также можете отправить 6 Runnable s.В этом случае 5 из них будут выполняться параллельно, и как только один Runnable завершит выполнение, будет выполнен шестой.

Кстати, я думаю, что документы совершенно ясно о поведении этого ExecutorService.

...