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 i =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 where I created two threads from the 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 two threads are accessing array simultaneously when array is already synchronized. Ideally when one thread access the array, it acquires the lock on that array and in this case, other thread should wait till the first thread doesnot leaves the lock on array.
Synchronized
is only triggered when two or more threads try to access the SAME data. In your case, your 2 threads both run a seperate instance of the ThreadDemo
class and hence a seperate ar
array. So the behaviour you are seeing is as 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 this case both threads are operating on the same data.