在同时处理时将数据刷新到DB

时间:2018-03-27 10:15:03

标签: java concurrency

我有8个线程同时将数据放入ArrayBlockingQueue,每个线程的代码如下所示:

import java.util.List;

public class PairProcessor implements Runnable {

private TagProcess tagProcess;

public PairProcessor(TagProcess tagProcess) {
    this.tagProcess = tagProcess;
}

@Override
public void run() {
    List<String[]> twoRow;
    while (true) {

        twoRow = tagProcess.getNext();

        if (twoRow == null)
            break;

        tagProcess.getAutotagResult().addAll(twoRow);

        if(tagProcess.getAutotagResult().size() >= 100) {
            System.out.println(tagProcess.getAutotagResult().size());
            tagProcess.getAutotagResult().clear();
        }
    }


    System.out.println("done");
}

}

现在我想刷新ArrayBlockingQueue中的数据,当它的每个大小达到某个阈值时,例如100.返回的ArrayBlockingQueue:

tagProcess.getAutotagResult()

我是否可以获得满足此要求的第一个线程,如果阻塞其余7个线程,让这个线程刷新数据(或做任何想做的事情),然后恢复其他线程。

1 个答案:

答案 0 :(得分:0)

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

public class PairProcessor implements Runnable {

private BlockingQueue<String[]> autotagResult;
private TagProcess tagProcess;
private CountDownLatch doneSignal;

public PairProcessor(TagProcess tagProcess) {
    this.autotagResult = tagProcess.getAutotagResult();
    this.doneSignal = tagProcess.getDoneSignal();
    this.tagProcess = tagProcess;
}

@Override
public void run() {
    List<String[]> twoRow;
    List<String[]> drainList;
    String name = "drainProcess";
    while (true) {

        twoRow = tagProcess.getNext();

        if (twoRow == null)
            break;

        autotagResult.addAll(twoRow);
        synchronized (name) {
            if (autotagResult.size() >= 100) {
                drainList = new ArrayList<>();
                autotagResult.drainTo(drainList, 100);
                System.out.println(drainList.size());
            }
        }
    }

    System.out.println("done");
    doneSignal.countDown();
}

}

更新了代码,我还不知道这段代码是否有效?它的规模是否很好? addAll仅用于测试目的,因为我希望确保共享的ArrayBlockingQueue与源List具有相同数量的数据。 {8}用于在8个线程完成其工作时发出主线程信号。