package thread;

import java.util.ArrayList;

public class add extends Thread {
	
	public static Object lock = new Object();
	private static ArrayList<Double> tmp = new ArrayList<Double>();	
	private static int Thread_Num = 4;
	private static int count = -1;
		
	private static double allsum = 0;
	private static double limit = 10000000;
	
    public void run() { // override Thread's run()
    	
    	int threadid;
    	synchronized(lock) {
    		threadid = ++count;
    	}
    	double sum = 0;
    	
    	for(int i=threadid;i<limit;i=i+Thread_Num) {
    		sum += tmp.get(i);
    	}
    	
    	synchronized(lock) {    	
    		allsum += sum;
    	}
    	
        System.out.println("Thread" + threadid + " finish!");
    }
    
    public static void main(String[] argv) {
    	  	
    	double testsum = 0;
		for(int i=0;i<limit;i++) {
			tmp.add((double) 1);
			testsum = testsum + 1;			
		}
    	double startTime = System.currentTimeMillis();   
    	
		Thread t[] = new Thread [Thread_Num];
    	for(int i=0;i<Thread_Num;i++) {
    		t[i] = new add();
    		t[i].start();
    	}   
    	
    	
    	try {
    		for(int i=0;i<Thread_Num;i++) {
        		t[i].join();
        	}
        } catch (InterruptedException e) {}
    	
    	System.out.println("right ans");
    	System.out.println(testsum);
    	
    	System.out.println("thread ans");
    	System.out.println(allsum);
    	
    	double endTime = System.currentTimeMillis(); 
    	System.out.println("Time : " + (endTime-startTime));
    	
    	
        
    }

    
}
