Two classes factor and addition
factor is having val variable that means it is shared across multiple threads (in the current application we are using two threads).
addition class is having a add variable it is also shared across multiple threads, because it's instantiated in factor class.
my question is
If
synchronized(this)
is used, which means that any of the two threads will lock on factor instance and increment val variable value till the loop exits. sosynchronized(this)
means here that we should not use any other instance variables. We have to use only the variables of factor instance inside the synchronized block?if
synchronized(addition)
means here that we have to use only add variable not the val variable of factor instance class?
There is a big confusion regarding this synchronization block . what i understood is synchronization block will lock on the object's instance and guard the operation and make it thread safe. But using different instance really means that it should guard only that particular instance variables not any other instance variables?
class Factor implements Runnable
{
int val = 0;
Addition addtion = new Addition();
@Override
public void run()
{
currInsLock();
diffInsLock();
}
// locking on the current instance which is this
// we will use synchronized(this)
public void currInsLock()
{
synchronized (this)
{
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---val value lock on this obj -->"+val++);
}
}
}
// locking on the different instance
public void diffInsLock()
{
synchronized (addtion)
{
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---val value lock on addition obj -->"+val++);
System.out.println(Thread.currentThread().getName()+"---add value lock on addition obj -->"+addtion.add++);
}
}
}
}
Class Action & ConcurrentDoubt:
public class Addition
{
public int add=0;
}
public class ConcurrentDoubt {
public static void main(String[] args)
{
Factor factor=new Factor();
Thread thread1=new Thread(factor);
Thread thread2=new Thread(factor);
thread1.start();
thread2.start();
}
}