So i m currently trying to understand concurrency. In my code I created a class "Summer" that features an int var. Its methode sumUP increments var by 2000000. My 2nd class is a Thread that takes Summer as an argument and calls its method sumUp. Both objects are initialized and started in my main Thread.
After my understanding the result should be arbitrary, basically giving my random numbers. The main Thread and the 2nd Thread create their own copy of the variable and change it independently.
My code is not Thread Safe at all, no volatile, no synchronized and still the answer is always 4000000. Can you please explain to my my error or is eclipse fixing Thread safety for me ? Thanks in advance :)
public class Main {
public static void main(String[]agrs) {
Summer summer = new Summer();
Thread t1 = new Thread(new MyRunnable(summer));
summer.sumUp();
t1.start();
}
}
public class MyRunnable implements Runnable {
private Summer summer;
public MyRunnable(Summer summer) {
this.summer = summer;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " hat gestartet R");
summer.sumUp();
System.out.println("Thread val =" + summer.val);
}
}
public class Summer {
public int val;
public void sumUp() {
for(int i=0; i<2000000; i++) {
increment();
}
System.out.println("MainThread val = " + val);
}
private void increment() {
val++;
}
}
(I know var should be private but it was quicker that way :) )