Use multi-threading to calculate sum of 10 thousand integers in Java
<p>I want to use multi-threading to calculate the sum of 10 thousand integers (from 1 to 10000). I have the basic understanding of synchronized key work. I know synchronized allows only one thread at a time during the execution and semaphore allows a certain number of threads at a time.</p>

<p>Here is my implementation using synchronized keyword:</p>

<pre><code>public class Testing {
private static int sum = 0;
private static int one = 1;
public synchronized static void increment() {
    sum = sum + one;
    one++;
}
public static void main(String[] args) {
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i &lt; 5000; i++) {
                increment();
            }
        }
    });
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i &lt; 5000; i++) {
                increment();
            }
        }
    });
    t1.start();;
    t2.start();
    try {
        t1.join();
        t2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(sum);
  }
}
</code></pre>

<p><strong>My solution</strong>: Divide the 10 thousand number into two parts. Use two threads to calculate each part.</p>

<p><strong>Question</strong>: Is there a better way to do that by using semaphore? I used synchronized here but should we use semaphore? How should we use semaphore to improve in this case?</p>