java - synchronize on array is not showing outcome as expected -
public class threaddemo implements runnable { integer ar [] = new integer[100]; @override public void run() { synchronized (ar) { system.out.println("start: in run method"); for(int =0; i<100;i++) { ar[i]=i; } for(int i=0;i<100; i++) { ar[i]= ar[i]*1000; system.out.println(ar[i]+"\t"); } system.out.println("end:in run method"); } }
other driver calls created 2 threads thread pool
executor task = executors.newfixedthreadpool(10); task.execute(new threaddemo()); task.execute(new threaddemo());
output :
start: in run method start: in run method 0 0 1000 1000 2000 2000 3000 3000
why 2 threads accessing array simultaneously when array synchronized. ideally when 1 thread access array, acquires lock on array , in case, other thread should wait till first thread doesnot leaves lock on array.
synchronized
triggered when 2 or more threads try access same data. in case, 2 threads both run seperate instance of threaddemo
class , hence seperate ar
array. behaviour seeing expected.
try replacing this:
executor task = executors.newfixedthreadpool(10); task.execute(new threaddemo()); task.execute(new threaddemo());
by this:
executor task = executors.newfixedthreadpool(10); threaddemo td = new threaddemo(); task.execute(td); task.execute(td);
in case both threads operating on same data.
Comments
Post a Comment