如何检查方法是否在并发环境中工作?

时间:2015-12-19 19:28:01

标签: java multithreading java.util.concurrent

我正在尝试理解多线程。 我有类和方法,看起来像:

public class Tree {

    ConcurrentHashMap<String, Apple> concurrentHashMap = new ConcurrentHashMap<String, Apple>();
/*This method should ONCE (@Before in jUnit4)create an array of apples*/
    public ConcurrentHashMap<String, Apple> getTreeApples(int NumOfApples) {
        for (int i = 0; i < NumOfApples; i++) {
            String appleNum = "5" + String.format("%010d", i);

            concurrentHashMap.put(appleNum, new Apple(appleNum, Long.valueOf("10")));
        }
        return concurrentHashMap;

    }

    ExecutorService executor = Executors.newCachedThreadPool();

/*This method get apple weight from array using different thread from the pool above*/
    public Long getAppleWeight (String appleNum) throws ExecutionException, InterruptedException {
        Long weight = null;
        Callable<Long> task = () -> {
            System.out.println("Thread: " + Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(1);
            return concurrentHashMap.get(appleNum).getWeight();};

        Future<Long> future = executor.submit(task);

        weight = future.get();
        System.out.println("Apple " + appleNum  + " weight is " + weight);
        return weight ;
    }
}   

我无法理解:

  1. getAppleWeight方法是否适合在多线程环境中工作?

  2. 它是否可以在多线程环境中正常工作(当方法getAppleWeight将由两个不同的系统同时调用时)?

  3. 如何检查(测试)它(由两个独立的系统调用)?

0 个答案:

没有答案