一个关于死锁的问题
class A{
public synchronized void foo(B b)
{
System.out.println("当前线程名:"+Thread.currentThread().getName()
+"进入了A的实例发foo方法");
try
{
Thread.sleep(200);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName()
+"尝试调用B实例的last()方法");
b.last();
}
public synchronized void last()
{
System.out.println("进入了A类的last()方法");
}
}
class B
{
public synchronized void bar(A a)
{
System.out.println("当前线程名:"+Thread.currentThread().getName()
+"进入了B的实例发foo方法");
try
{
Thread.sleep(200);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("当前线程名:"+Thread.currentThread().getName()
+"尝试调用A实例的last()方法");
a.last();
}
public synchronized void last()
{
System.out.println("进入了B类的last()方法");
}
}
public class DeadLockDemo implements Runnable
{
A a = new A();
B b = new B();
public void info()
{
Thread.currentThread().setName("主线程");
a.foo(b);
System.out.println("进入主线程之后");
}
@Override
public void run()
{
Thread.currentThread().setName("副线程");
b.bar(a);
System.out.println("进入副线程之后");
}
public static void main(String[] args)
{
DeadLockDemo d = new DeadLockDemo();
d.info();
Thread t1 = new Thread(d);
t1.start();
/**
*把d.info()放在前面就能正常运行
*DeadLockDemo d = new DeadLockDemo();
*d.info();
*Thread t1 = new Thread(d);
*t1.start();
*/
}
}