class A
{
synchronized void foo(B b)
{
String name=Thread.currentThread().getName();
System.out.println(name+ " entered A.foo ");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(name+ " trying to call B.last()");
b.last();
}
synchronized void last()
{
System.out.println("inside A.last");
}
}
class B
{
synchronized void bar(A a)
{
String name=Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last()
{
System.out.println("inside A.last");
}
}
class Deadlock implements Runnable
{
A a=new A();
B b=new B();
Deadlock()
{
Thread.currentThread().setName("MainThread");
new Thread(this).start();
a.foo(b); //get lock on a in this thread.
System.out.println("back in main thread");
}
public void run()
{
Thread.currentThread().setName("RacingThread");
b.bar(a); //get lock on a in other thread.
System.out.println("back in other thread");
}
public static void main(String[] args)
{
new Deadlock();
}
}大家帮忙,线程的代码我看不懂,感谢为什么有死锁,感谢
{
synchronized void foo(B b)
{
String name=Thread.currentThread().getName();
System.out.println(name+ " entered A.foo ");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(name+ " trying to call B.last()");
b.last();
}
synchronized void last()
{
System.out.println("inside A.last");
}
}
class B
{
synchronized void bar(A a)
{
String name=Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last()
{
System.out.println("inside A.last");
}
}
class Deadlock implements Runnable
{
A a=new A();
B b=new B();
Deadlock()
{
Thread.currentThread().setName("MainThread");
new Thread(this).start();
a.foo(b); //get lock on a in this thread.
System.out.println("back in main thread");
}
public void run()
{
Thread.currentThread().setName("RacingThread");
b.bar(a); //get lock on a in other thread.
System.out.println("back in other thread");
}
public static void main(String[] args)
{
new Deadlock();
}
}大家帮忙,线程的代码我看不懂,感谢为什么有死锁,感谢
2.由哪个线程执行了sleep,就由那个线程去睡觉,并把cpu的执行权释放,交给另外一个线程;
所以,当程序执行到b.last()的时候,当前线程需要进入另一个线程,当然就死锁了
{
Thread.currentThread().setName("MainThread");
new Thread(this).start();
a.foo(b); //get lock on a in this thread.
System.out.println("back in main thread");
}
这里执行new Thread(this).start();启动新线程之后,新线程并不马上执行,有可能继续执行主线程的代码,为了在住线程结束前执行新线程,所以必须让主线程Thread.sleep(1000);以便新线程获得处理机.
新线程执行到b.bar(a)中的a.last()方法时,因为bar(a)方法是synchronized修饰的,所以把对象b的标志位置为0.这时
主线程试图执行b.last(),因为b.last()方法是synchronized修饰的,而b的标志位为0,进不去
新线程试图执行a.last(),因为a.last()方法是synchronized修饰的,而a的标志位为0,进不去死锁就发生了.