关于synchronized修饰方法和代码块时锁的对象
synchronized修饰方法
- 修饰普通方法
锁的是当前方法所属的类创建的实例对象,不同的实例对象互不干扰
public synchronized void test2()
{
int i = 5;
while (i-- > 0)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
try
{
Thread.sleep(500);
}
catch (InterruptedException ie)
{
}
}
}
- 修饰静态方法
锁的是当前方法所属的类,不同的实例对象互不干扰
public static synchronized void test2()
{
int i = 5;
while (i-- > 0)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
try
{
Thread.sleep(500);
}
catch (InterruptedException ie)
{
}
}
}
synchronized修饰代码块
- 锁类
锁的是TestSynchronized2
类,该类的所有实例对象对锁互斥
public class TestSynchronized2
{
public void test1()
{
synchronized (TestSynchronized2.class)
{
int i = 5;
while (i-- > 0)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
try
{
Thread.sleep(500);
}
catch (InterruptedException ie)
{
}
}
}
}
}
- 锁this
锁的是实例对象this,不同的实例对象互不干扰
public class TestSynchronized
{
public void test1()
{
synchronized (this)
{
int i = 5;
while (i-- > 0)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
try
{
Thread.sleep(500);
}
catch (InterruptedException ie)
{
}
}
}
}
}