I have a simple Java program with 3 threads, each incrementing and then printing a variable counter. The java code is-
public class test implements Runnable {
private int counter=0;
public static void main(String args[]){
test t=new test();
Thread t1=new Thread(t,"THREAD 1");
Thread t2=new Thread(t,"THREAD 2");
Thread t3=new Thread(t,"THREAD 3");
t1.start();
t2.start();
t3.start();
}
public void run(){
counter=counter+1;
System.out.println(Thread.currentThread().getName()+" "+ counter);
}
}
Understanding that the method run is not synchronized the threads can interleave in any fashion giving any result but the result I get mostly(I've run the program multiple times) is-
THREAD 1 2
THREAD 3 3
THREAD 2 2
I don't understand how come 1 is never printed and even after printing 3, 2 is again printed(since the most recent value of counter has been set to 3, as it is printed).
Also, is the variable counter shared among the 3 threads? It will be shared if I make it static but what in this case.
Please explain.
tinto your 3 threads, hence they all use the samecounterinstance. Also, the fieldcounteris being modified by multiple threads and has no synchronization, so your computations are probably only cpu-memory and not stored in actual memory, which can lead to funky results