class A
{
/*
synchronized同步代码块时允许任何对象来作为同步监视器,如:synchronized(obj);
同步方法时无须显式指定同步监视器,同步方法的同步监视器是this,即对象本身.
*/
public synchronized void foo(B b)
{
System.out.println("当前线程名:"+Thread.currentThread().getName()+"进入了A实例的foo方法");
try
{
Thread.sleep(200);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName()+"企图调用B实例的last方法");
b.last();//锁定A对象后申请锁定B对象 @a
}
/*执行此方法时必须锁定B对象*/
public synchronized void last()
{
System.out.println("进入了A类的last方法内部");
}
}
class B
{
public synchronized void bar(A a)
{
System.out.println("当前线程名:"+Thread.currentThread().getName()+"进入了B实例的bar方法");
try
{
Thread.sleep(200);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName()+"企图调用A实例的foo方法");
a.last();//锁定B对象后申请锁定A对象 @b
}
public synchronized void last()
{
System.out.println("进入了B类的last方法内部");
}
}
public class DeadLock implements Runnable
{
A a=new A();
B b=new B();
public void init()
{
Thread.currentThread().setName("主线程");
a.foo(b);//锁定A对象 @c
System.out.println("进入了主线程之后");
}
public void run()
{
Thread.currentThread().setName("副线程");
b.bar(a);//锁定B对象 @d
System.out.println("进入了副线程之后");
}
public static void main(String[] args)
{
/*
@c锁定了A对象, @d锁定了B对象 。@c方法中@a申请锁定B对象,@d方法中@b申请锁定A对象,互相等待,因此发生死锁。
*/
DeadLock deadLock=new DeadLock();
new Thread(deadLock).start();
deadLock.init();
}
}
疯狂JAVA讲义 读书笔记