更新变量&将数字添加到两个不同的列表

时间:2017-09-19 13:58:02

标签: java multithreading blockingqueue

本周我刚开始做线程,我有点坚持练习。

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    public class RandomNumberConsumer implements Runnable {

    ArrayBlockingQueue<Integer> numbersProduced;

    public RandomNumberConsumer(ArrayBlockingQueue<Integer> numbersProduced) {
        this.numbersProduced = numbersProduced;
    }
    //Should eventually hold the sum of all random number consumed
    int sumTotal = 0;
    List<Integer> below50 = new ArrayList();
    List<Integer> aboveOr50 = new ArrayList();

    @Override
    public void run() {
        //In this exercise, we start four threads, each producing 100 numbers, so we know how much to consume
        for (int i = 0; i < 400; i++) {
            try {
                System.out.println("first" + numbersProduced.take());
                System.out.println("second" + numbersProduced.take());
                 System.out.println("third" + numbersProduced.take());
                 System.out.println("fourth" + numbersProduced.take());

            } catch (InterruptedException ex) {
                Logger.getLogger(RandomNumberConsumer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    public int getSumTotal() {
        return sumTotal;
    }

    public List<Integer> getBelow50() {
        return below50;
    }

    public List<Integer> getAboveOr50() {
        return aboveOr50;
    }

}

基本上我不了解的是如何更新sumTotal变量以显示所有消耗的随机数,因为它们存储在ArrayBlockingQueue&lt;&gt;中以及如何将它们插入50以下或50个列表中。

1 个答案:

答案 0 :(得分:0)

如果在run方法中不使用numbersProduced.take()并定义一个新函数,即使在RandomNumberConsumer类中也是如此?

int foo() throws InterruptedException{ //because of take function
int a=numbersProduced.take();
if(a<50)
    below50.add(a);
else
    over50.add(a);
sumTotal=sumtTotal+a;
return a;
}

现在在运行中调用foo而不是numbersProduced.take()

我必须告诉你,我希望你知道它:如果你使用修改相同变量的线程,你必须使用信号量或同步方法。

Ps:抱歉英语不好:)