Hello everyone i am doing a simple program that computes the sum of numbers from 0 to 99. I was reading on threads in java and I'm trying to understand how it works especially multithreading so i wrote a simple program to understand the concept. But the output from my program is different as it outputs 0 and 4950. It seems there are 2 threads running? The main thread and then object thread a? I have a problem from output cause they are not synchronized. I hope i am on the right track but am not sure and need guidance. Could someone please explain how to use the synchronized to solve this problem. Having trouble understanding it?
public class Testing {
public static void main(String[] args) {
ThreadB b = new ThreadB();
Thread a = new Thread(b);
a.start();
System.out.println(b.total);
}
}
class ThreadB extends Thread {
int total;
public ThreadB() {
this.total = 0;
}
public synchronized int total() {
for(int i = 0; i < 100; i++) {
total += i;
}
return total;
}
public void run() {
System.out.println(total());
}
}