public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) { exec.execute(new Entrance(i)); } // Run for a while, then stop and collect the data: TimeUnit.SECONDS.sleep(3); // Marvin: main线程设置条件,从而使得 Entrance 线程都停下 Entrance.cancel(); // Marvin: exec不再接受新task,运行中的则停下来 exec.shutdown(); if (!exec.awaitTermination(250, TimeUnit.MILLISECONDS)) print("Some tasks were not terminated!"); // Marvin: 这里是在main线程中调用 Entrance.getValue(),这和 Entrance.run()是不同的线程。所以,Entrance.run()中,才同步更新 print("Total: " + Entrance.getTotalCount()); print("Sum of Entrances: " + Entrance.sumEntrances()); }
public static int sumEntrances() { int sum = 0; for (Entrance entrance : entrances) sum += entrance.getValue(); return sum; }