当线程排队时,共享列表未更新



我有一个代码,它有两个执行者,executorShopsexecutorSections,第一个是不重要的,虽然

我创建了尽可能多的节(在这个例子中是三个),但是,只有两个被同时执行。

每个任务更新一个共享列表,但是,问题是只有前两个线程正确地更新它。已经排队的第三个线程不会更新它。

下面是创建任务的代码:

Runnable task = () -> {
    LOG.info("Llamamos al ScraperManager para obtener el scraper de " + shop.getName());
    Scraper scraper = ScraperManager.getScraper(shop);
    LOG.info("Scraper de " + shop.getName() + " obtenido");
    ExecutorService executorSections = Executors.newFixedThreadPool(Properties.MAX_THREADS_SECTIONS);
    Set<Callable<List<Product>>> listOfTasks = new HashSet<>();    
    for (int j = 0; j < shop.getSections().size(); j++)
    {
        final Section section = shop.getSections().get(j);
        Callable<List<Product>> taskSection = () -> scraper.scrap(shop, section);
        listOfTasks.add(taskSection);                    
    }
    try 
    {
        List<Future<List<Product>>> listOfFutures = executorSections.invokeAll(listOfTasks);
        List<Product> productList = listOfFutures.get(shop.getSections().size() - 1).get();
        RestClient restClient = new RestClient(new URL(Properties.SERVER));
        restClient.saveProducts(productList, shop);
        countDownLatch.countDown();
        executorSections.shutdown();
    } catch (InterruptedException | ExecutionException ex ) {
        ...
    } catch (MalformedURLException ex) {
        ...
    }
};

下面是废弃任务:

public class ShopScraper implements Scraper
{
    private static List<Product> productList = Collections.synchronizedList(new ArrayList<>());
    private static final ThreadLocal<Boolean> threadFinished = 
            new ThreadLocal<Boolean>() 
            {
                @Override 
                protected Boolean initialValue() 
                {
                    return false;
                }
            };
    @Override
    public List<Product> scrap(Shop shop, Section section) throws IOException
    {
        // add products to the list
        return productList;
    }
}

EDIT:如果我将线程数限制为1,则第二个和第三个线程不更新列表。

有谁知道我做错了什么吗?

提前致谢

一个线程=一个任务。

    // MAX_THREADS_SECTIONS = 2
    ExecutorService executorSections = Executors.newFixedThreadPool(Properties.MAX_THREADS_SECTIONS);

将池大小限制为只有2个线程,因此只有2个任务将并行运行。

增加这个值,所有的任务将在同一时间运行

最新更新