0

我已经开始研究一个项目,在这个项目中,我需要将每次调用中的sizeofbeAttributes与之前的size.

下面是我的代码-

public static void main(String[] args) {

    final int noOfThreads = 2;

    //create thread pool with given size 
    ExecutorService service = Executors.newFixedThreadPool(noOfThreads);


    for (int i = 0, i< noOfThreads; i++) {
        service.submit(new ThreadTask());
    }

    // wait for termination        
    service.shutdown();
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

    System.out.println(ThreadTask.count_size);
}

class ThreadTask implements Runnable {

    public static int count_size = 0;

    @Override
    public void run() {

        while(time < 10 minutes) {
            try {

            ...

            List<BEAttribute<?>> beAttributes = beClient.getBEAttributes(columnsList);

            // Now I need to sum the beAttributes.size in every call

                final int size = beAttributes.size;
                count_size = count_size + size;
            ...

            } catch (InterruptedException e) {

            }
        }
    }

问题陈述:-

假设在 while 循环中,对于第一次调用getBEAttributes方法,我得到beAttributes.size20. 然后我应该将它存储20 number在一些静态整数中。现在在对方法的其他调用中getBEAttributes,我得到了beAttributes.sizeas 40,那么我应该将它添加40到 previous 20。所以现在静态整数将变为 60。并继续执行此过程,直到程序完成。并从主线程打印相同的静态整数。

我目前正在做的方式是线程安全的吗?我想我做增量的方式有问题。如果是的话,有人可以帮助我正确的方法吗?

4

2 回答 2

0

这并不是真正的线程安全,因为您有多个线程访问同一个变量count_size. 我的建议(简单修复)是使用 aAtomicInteger而不是 int。它们具有原子(即保证互斥)方法getAndAdd(int size)addAndGet(int size)您可以使用它们来添加它。为了使其线程安全,您还需要使变量 volatile - 这确保不进行本地缓存。例如:

public static volatile AtomicInteger countSize = new AtomicInteger();

//...
while() {
    //...
    countSize.getAndAdd(beAttributes.size);
    //...
}

要获取 int 值:ThreadTask.countSize.get().

您还可以使用自己的锁创建自己的方法以添加到变量中,例如:

private static volatile int countSize = 0;
private static Object lock = new Object();


private static void addToSize(int i) {
    synchronized(lock) {
        countSize+=i;
    }
}
public static int getCount() {
    synchronized(lock) { //it is good practice to synch getters too - although not entirely necessary with ints.
        return countSize;
    }
}
于 2013-03-20T04:05:38.093 回答
0

以下操作不是原子的:</p>

count_size = count_size + size;

试试下面:

public static   AtomicInteger countSize = new AtomicInteger()

countSize.getAndAdd(beAttributes.size);
于 2013-03-20T04:27:38.947 回答