首先给到需要获取和计算的股票,存入一个文本中,如stocks.txt
AAPL,2505 AMGN,3406 AMZN,9354 BAC,9839 BMY,5099 CAT,8463 C,1500 CMCSA,6144 CSCO,4589 CVX,9696 DIS,4804 DOW,3654 EMC,4835 FDX,4753 GD,3919 GE,7003 GOOG,6631 HAL,2593 HPQ,6157 IBM,1728 INTC,4053 JPM,1665 LMT,4402 MET,3712 MO,3764 MSFT,2813 NKE,6447 NSC,5537 ORCL,7136 PFE,659 RTN,5063 S,8219 SO,7175 TXN,1410 USB,3099 VZ,9826 WMT,6478
然后定义个抽象类,用于读取这个stocks.txt中存放的股票信息,并计算出股票的总值和读取花费的时间。代码如下:
public abstract class AbstractNAV { public static Map<String, Integer> readTickers() throws IOException { final BufferedReader reader = new BufferedReader(new FileReader("d:/stocks.txt")); final Map<String, Integer> stocks = new HashMap<String, Integer>(); String stockInfo = null; while((stockInfo = reader.readLine()) != null) { final String[] stockInfoData = stockInfo.split(","); final String stockTicker = stockInfoData[0]; final Integer quantity = Integer.valueOf(stockInfoData[1]); stocks.put(stockTicker, quantity); } return stocks; } public void timeAndComputeValue() throws ExecutionException, InterruptedException, IOException { final long start = System.nanoTime(); final Map<String, Integer> stocks = readTickers(); final double nav = computeNetAssetValue(stocks); final long end = System.nanoTime(); final String value = new DecimalFormat("$##,##0.00").format(nav); System.out.println("Your net asset value is " + value); System.out.println("Time (seconds) taken " + (end - start)/1.0e9); } public abstract double computeNetAssetValue( final Map<String, Integer> stocks) throws ExecutionException, InterruptedException, IOException; }
然后,我们用传统的单线程方式,依次去读取并计算股票,并打印总价和花费的时间,代码如下:
public class SequentialNAV extends AbstractNAV { public double computeNetAssetValue( final Map<String, Integer> stocks) throws IOException { double netAssetValue = 0.0; for(String ticker : stocks.keySet()) { netAssetValue += stocks.get(ticker) * YahooFinance.getPrice(ticker); } return netAssetValue; } public static void main(final String[] args) throws ExecutionException, IOException, InterruptedException { new SequentialNAV().timeAndComputeValue(); } }
由于网络问题,我这里运行之后,得到的结果是:
Your net asset value is $18,317,338.21 Time (seconds) taken 18.080151543
紧接着,我们用多线程方式,读取并计算,并打印总价和时间花费
public class ConcurrentNAV extends AbstractNAV { public double computeNetAssetValue(final Map<String, Integer> stocks) throws InterruptedException, ExecutionException { final int numberOfCores = Runtime.getRuntime().availableProcessors(); final double blockingCoefficient = 0.9; final int poolSize = (int)(numberOfCores / (1 - blockingCoefficient)); System.out.println("Number of Cores available is " + numberOfCores); System.out.println("Pool size is " + poolSize); //Callable接口的实例,用于被另一个线程执行call(),并返回,无返回则抛出异常。 //它类似于Runnable接口,而Runnable 不会返回结果,并且无法抛出经过检查的异常。 final List<Callable<Double>> partitions = new ArrayList<Callable<Double>>(); for(final String ticker : stocks.keySet()) { partitions.add(new Callable<Double>() { public Double call() throws Exception { return stocks.get(ticker) * YahooFinance.getPrice(ticker); } }); } //定义线程池 final ExecutorService executorPool = Executors.newFixedThreadPool(poolSize); //Future接口的实例,通过get()方法,获取多线程下异步的计算结果。 //必要时,计算完成前可阻塞该方法,可通过cancel()取消计算,一旦计算完成,则无法取消。 final List<Future<Double>> valueOfStocks = executorPool.invokeAll(partitions, 10000, TimeUnit.SECONDS); double netAssetValue = 0.0; for(final Future<Double> valueOfAStock : valueOfStocks) netAssetValue += valueOfAStock.get(); executorPool.shutdown(); return netAssetValue; } public static void main(final String[] args) throws ExecutionException, InterruptedException, IOException { new ConcurrentNAV().timeAndComputeValue(); } }
在跟上面同等的网络环境下,这段代码运行之后的结果为:
Number of Cores available is 4 Pool size is 40 Your net asset value is $18,317,338.21 Time (seconds) taken 0.715660335