1

ファイルに順番に書き込む必要がある ExecutorService でタスクをインスタンス化しようとしているため、33 個のタスクが存在する場合、順番に書き込む必要があります...

LinkedBlockingQueue と ReentrantLock を使用して順序を保証しようとしましたが、フェア モードで理解していることから、ExecutorService が作成した x スレッドの中で最も若いものにロックが解除されます。

private final static Integer cores =      Runtime.getRuntime().availableProcessors();
private final ReentrantLock lock = new ReentrantLock(false);
private final ExecutorService taskExecutor;

コンストラクタで

taskExecutor = new ThreadPoolExecutor
        (cores, cores, 1, TimeUnit.MINUTES, new LinkedBlockingQueue());

そのため、入力ファイル ピア タスクのクォータを処理します。

if(s.isConverting()){
   if(fileLineNumber%quote > 0) tasks = (fileLineNumber/quote)+1;
   else tasks = (fileLineNumber/quote);
   for(int i = 0 ; i<tasks || i<1 ; i++){
      taskExecutor.execute(new ConversorProcessor(lock,this,i));
   }
}

タスクが行う

public void run() {
    getFileQuote();
    resetAccumulators();
    process();
    writeResult();
}

そして私の問題はここで発生します:

private void writeResult() {
    lock.lock();
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter("/tmp/conversion.txt",true));
        Integer index = -1;
        if(i == 0){
            bw.write("ano dia tmin tmax tmed umid vento_vel rad prec\n");
        }
        while(index++ < getResult().size()-1){
            bw.write(getResult().get(index) + "\n");
        }
        if(i == controller.getTasksNumber()){ 
            bw.write(getResult().get(getResult().size()-1));
        }
        else{ 
            bw.write(getResult().get(getResult().size()-1) + "\n");
        }
        bw.close();
    } catch (IOException ex) {
        Logger.getLogger(ConversorProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } finally { 
        lock.unlock(); 
    }

}
4

1 に答える 1

0

ファイルへの出力の書き込みを除いて、すべてを同時に実行する必要があるように見えます。これは、オブジェクトの作成順序で実行する必要があります。

ファイルに書き込むコード、writeResult()メソッドをスレッド コードから取り出し、代わりに、メソッドによって作成された文字列を返す Future を作成しprocess()、Future を にロードしますArrayList<Future<String>>。次に、ArrayList を反復処理し、for ループget()で各 Future を呼び出し、BufferedWriter または PrintWriter を使用して結果をテキスト ファイルに書き込みます。

于 2014-09-28T01:06:26.167 に答える