简体   繁体   English

使用线程池计算所需的总时间

[英]Calculate the total time required using Thread Pool

I get struck in a problem in the Codewars that asks to calculate the total time for the customer queue for the self-checkout process in the supermarket and asked to use the concept of the thread pool. 我在Codewars中遇到一个问题,该问题要求计算超市中自助结帐流程的客户队列的总时间,并要求使用线程池的概念。 So, I just Googled it and find that a thread pool pattern consists of a number m of threads, created to perform a number n of tasks concurrently. 因此,我只用Google搜索它,发现线程池模式包含m个线程,这些线程被创建为同时执行n个任务。 For the current problem the I guess the threads will be the number of checkout booths and the number of the tasks will be equal to the number of the customers. 对于当前的问题,我想线程将是结帐亭的数量,而任务的数量将等于客户的数量。 Below are the instructions for the problem: 以下是该问题的说明:

customers: an array of positive integers representing the queue. 客户:代表队列的正整数数组。 Each integer represents a customer, and its value is the amount of time they require to check out. 每个整数代表一个客户,其值是他们需要结帐的时间。 n: a positive integer, the number of checkout tills. n:一个正整数,结算位数。 The function should return an integer, the total time required. 该函数应返回一个整数,即所需的总时间。

Assume that the front person in the queue (ie the first element in the array/list) proceeds to a till as soon as it becomes free. 假设队列中的最前面的人(即数组/列表中的第一个元素)一到空闲就进行到耕种。

public static int solveSuperMarketQueue(int[] customers, int n) {
  return 0;
}

I think the solution needs to be to split the customers randomly to the self-checkout booths and count how much time it takes to cleared up all those queues using the threading. 我认为解决方案需要将客户随机分配到自助结帐亭,并计算使用线程清理所有这些队列所花费的时间。 I find this sample code for the thread pool provided below: 我发现以下提供的thread pool示例代码:

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

class WorkerThread implements Runnable {

    private String command;

    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+' End.');
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}

public class SimpleThreadPool {

    public static void main(String[] args) {

        // I think this will be n in the provided method  
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // loop will iterate till **customers.length** time 
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread('' + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println('Finished all threads');
    }

}

How to use the above code to compute the total time ? 如何使用上面的代码来计算总时间? I also appreciate any other suggestion. 我也很感谢其他建议。

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Solution {
    private final static long SCALE = 100L;
    static class Customer implements Callable<Void> {

        private final long timeToWait;
        private final CountDownLatch exitLatch;

        Customer(int timeToWait, CountDownLatch exitLatch) {
            this.timeToWait = timeToWait * SCALE;
            this.exitLatch = exitLatch;
        }

        @Override
        public Void call() throws Exception {
            Thread.sleep(this.timeToWait);
            this.exitLatch.countDown();
            return null;
        }
    }


    public static int solveSuperMarketQueue(int[] customers, int n) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(n);
        CountDownLatch exitLatch = new CountDownLatch(n);
        Queue<Customer> queue = new LinkedList<>();
        for (int i : customers) {
            queue.add(new Customer(i, exitLatch));
        }

        long startTime = System.currentTimeMillis();
        service.invokeAll(queue);
        exitLatch.await();
        long wholeTime = System.currentTimeMillis() - startTime;
        service.shutdown();

        return (int) (wholeTime / SCALE + (wholeTime % SCALE == 0 ? 0 : 1));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM