Hi, I'm trying to get the threads synchronized, but the output I get is still wrong:
Expected sum: 20000000
Actual sum: 10000000
Do I use synchronized wrong, or do I put it in a wrong place?
class TestThread extends Thread
{
public void run()
{
for (int i = 1; i <= SampleRace.N1; i++)
{
//System.out.println(SampleRace.sum);
SampleRace.sum = SampleRace.calcsum(SampleRace.sum);
}
} // run
} // class TestThread
public class SampleRace
{
public static final int N1 = 1000;
public static final int N2 = 10000;
public static int sum = 0;
public synchronized static int calcsum(int sum)
{
int tmp;
tmp = sum;
for (int i = 0; i < N2; i++)
tmp = tmp + 1;
//System.out.println(sum);
return(tmp);
}
public static void main(String[] args) throws InterruptedException
{
// start the tasks
TestThread t1 = new TestThread();
t1.start();
TestThread t2 = new TestThread();
t2.start();
// wait for the tasks to finish
t1.join();
t2.join();
// print results
System.out.println("Expected sum: " + 2 * N1 * N2);
System.out.println("Actual sum: " + sum);
} // main
} // class SampleRace
Thanks,
Waldis