【发布时间】:2016-10-14 10:17:40
【问题描述】:
1) 如果使用了 synchronized(this),这意味着两个线程中的任何一个都将锁定因子实例并增加 val 变量值直到循环退出。 所以 synchronized(this) 在这里意味着我们不应该使用任何其他实例变量。我们只能在同步块中使用因子实例的变量吗?
2) 如果 synchronized(addition) 在这里意味着我们只能使用 add 变量而不是 factor 实例类的 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++);
}
}
}
}
加法类:
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();
}
}
【问题讨论】:
标签: java multithreading synchronization