簡體   English   中英

Java多線程問題-使用者/生產者模式

[英]Java multithreading issue - Consumer/Producer pattern

試圖解決此問題,但事實證明這很困難。

我有兩個線程,一個是生產者,另一個是消費者。 全部在單獨的類中。 這兩個線程獨立運行。 生產者將大約8-12個文件夾用於輸入。 然后,它會同時轉換所有文件,並放置在一個名為“ readyToLoad”的共享文件夾中。 生產者線程完成后,消費者線程現在進入“ readyToLoad”文件夾並開始處理翻譯后的文檔。

現在,當使用者處理翻譯的文檔時,不允許生產者將更多的翻譯文件放入“ readyToLoad”文件夾。

我的問題是,如何防止使用者鎖定“ readyToLoad”文件夾? 我該如何處理這種情況?

對冗長的文字表示歉意,但我認為這將有助於您了解問題所在。 感謝您的幫助。

UPDATE:添加了使用者代碼(在加載過程中執行加載並鎖定文件的代碼)

public class LoadManager {
protected static final Logger logger = KCLogger.getLogger();
 ArrayList<Loader> threads = new ArrayList<Loader>();
 KCBLConfig config;
 private static final ExecutorService service = Executors.newFixedThreadPool(10);
 public LoadManager(KCBLConfig config) {
    this.config = config;
 }

public void start() throws Exception {
    logger.log(Level.INFO, "Starting loading threads.");
    try {
        TreeMap<String, ConnectionHandler> connectionHandlers = config.getConnectionHandlers();
        Iterator i = connectionHandlers.keySet().iterator();
        while (i.hasNext()) {

            ConnectionHandler connectionHandler = connectionHandlers.get((String) i.next());

            for (LoadFolder loadFolder : connectionHandler.getKcXMLFolders()) {
               Loader loader = new Loader(loadFolder.getId(), loadFolder, config.getConnectionHandlers());
               Thread loaderThread = new Thread(loader);
                loaderThread.start();   
               //service.submit(loader);
              // service.shutdown();
               //service.awaitTermination(1, TimeUnit.MILLISECONDS);
                threads.add(loader);
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "There was an error starting the loaders. Stopping all loader threads.", e);
        this.stop();
        throw e;
    }
    logger.log(Level.INFO, "All loader threads created. There are " + threads.size() + " loader threads");
}

Java生產者/消費者習慣用法通常現在使用BlockingDeque完成。

我將為生產者和消費者提供單獨的文件夾。 為什么要承擔這種復雜性?

您只能通過synchronized方法在Java http://en.wikipedia.org/wiki/Monitor_( synchronized )中使用Monitor

如果我理解正確,那么您在生產者和消費者之間沒有任何通知機制。 生產者將文件存儲在一個文件夾中,而消費者則有一個無限循環,該循環從該文件夾中讀取所有文件並將它們移到其他位置。

那就是問題所在。 這是我要解決的方法。

生產者和消費者都應共享一個BlockingQueue實例。 生產者每次完成文件的生成(文件已​​完全寫入共享文件夾)時,都會將文件名添加到阻止隊列中。

使用者從隊列中獲取文件名。 這是一項阻止操作,因此將使用者隔離到文件名可用之前。 當使用者從隊列中獲得文件名時,它將讀取該文件(並且僅此文件),並對其進行任何操作。

這有幾個優點:

  • 沒有生產者和消費者同時訪問一個文件的風險
  • 您可以擁有任意數量的生產者和消費者
  • 消費者不會無休止地掃描目錄
  • 您可以為隊列設置一個邊界,以避免產生過多的文件,並讓消費者有機會跟上生產者的步伐。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM