# 5 days
bugs.vn/io/7TIIS
# Text
file_download DOWNLOAD FILE
package multithreading;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
public class Exercise304 {
    public static MyClass myClass = new MyClass();
   
    public static void main(String[] args) throws Exception {
        IncreaseSumTask increaseTask = new IncreaseSumTask();
        ExecutorService executor = Executors.newCachedThreadPool();
 
        for (int i = 0; i < 1000; i++) {
            executor.execute(increaseTask);
        }
 
        executor.shutdown();
        while(!executor.awaitTermination(60, TimeUnit.SECONDS)) {
             Thread.sleep(60000);
         }  
 
        // Wait until all tasks are finished
        while (!executor.isTerminated()) {
        }
 
        System.out.println("What is sum? " + myClass.getSum());
    }
 
    private static class IncreaseSumTask implements Runnable {
        @Override
        public void run() {
            synchronized (myClass) {
                myClass.increaseSumByOne();
            }
        }
    }
 
    private static class MyClass {
        private Integer sum = new Integer(0);
 
        public Integer getSum() {
            return sum;
        }
 
        public void increaseSumByOne() {
            sum = sum + 1;
        }
    }
}