SHE SHE - 6 months ago 23
Java Question

Use multi-threading to calculate sum of 10 thoursand integers in Java

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.

Here is my implementation using synchronized keyword:

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 < 5000; i++) {
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5000; i++) {
increment();
}
}
});
t1.start();;
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sum);
}
}


My solution: Divide the 10 thousand number into two parts. Use two threads to calculate each part.

Question: 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?

Answer

If you are looking to sum a no of integers instead look at ForkJoinTask https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinTask.html

If you are trying to understand semaphore usage check Semaphore simple sample

EDIT: change your increment() to

public static void increment() 
    {
        try
        {
            semaphore.acquire();
        }
        catch (InterruptedException e)
        {
            //process excp
        }
        sum = sum + one;
        one++;
        semaphore.release();
    }

and add

private static Semaphore semaphore = new Semaphore(1); 

as class variable

But as others have noted this is not the right way to split the problem. Also, if you are looking for wait()/notify() semaphore model, you'd still have to use synchronized.