兩類因子和加法確認同步概念
因子具有VAL變量,這意味着它在多個線程共享的(在目前的應用中,我們使用的是兩個線程)。
另外類有一個添加變量,它也在多個線程之間共享,因爲它在因子類中實例化。
我的問題是
如果
synchronized(this)
被使用,這意味着任何兩個線程將鎖定因素實例,並增加VAL變量的值,直到循環退出。 所以synchronized(this)
這裏意味着我們不應該使用任何其他實例變量。我們只能在synchronized塊中使用因子實例的變量嗎?if
synchronized(addition)
這裏意味着我們只需要使用添加變量而不是因子實例類的val變量?
關於這個同步塊存在很大的困惑。 我明白的是同步塊會鎖定對象的實例,並防止操作並使其安全。但使用不同的實例真的意味着它應該只保護特定的實例變量而不是其他任何實例變量?
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++);
}
}
}
}
類操作& 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();
}
}
根據答案提供的同步(加法)是正確的,因爲加法,加上mutable狀態是p謹慎守衛。由於增量操作在同步(加法)中使用,因此val可變狀態未得到適當的保護,這意味着val變量在同步(加法)中被訪問。如果我只在同步內使用val變量(this)並且只在同步內添加變量(加法),那麼這兩個變量都會被正確保護,但是有什麼區別 – amt14779