multithreading - Java Synchronisation with and without static variable -
i have been studying synchronization in java , tried run following program
public class example { public static void main(string[] args) { counter countera = new counter(); counter counterb = new counter(); thread threada = new counterthread(countera); thread threadb = new counterthread(counterb); threada.start(); threadb.start(); } } class counterthread extends thread { protected counter counter = null; public counterthread(counter counter){ this.counter = counter; } public void run() { for(int i=0; i<2; i++){ counter.add(i); } } } class counter { long count = 0; public synchronized void add(long value){ this.count += value; system.out.println(this.count); } }
when run above code , gives me same output when run example class java application or when debug example class
0 1 0 1
but if modify access modifier of count variable of counter class static mentioned below :
static long count = 0;
and if try run example class output
0 1 0 2
but when debug example class output
0 1 1 2
can me understand difference. in advance , apologies because new multithreading concepts
each instance has own copy of instance variable(s) share static variable. have 2 instances of class , 2 threads operating on these instances:
counter countera = new counter(); counter counterb = new counter(); thread threada = new counterthread(countera); thread threadb = new counterthread(counterb);
so effect clear. when count
non-static, 2 threads not affect count
of 2 different objects. when count
static, 2 threads work on same variable shared 2 instances.
when have 2 independent threads in action, execution order dynamic depending on how thread scheduler picks thread execute. using debugger not affect , infact may see different result normal execution of program.
Comments
Post a Comment