class A{
synchronized void foo(B b){
String name = Thread.currentThread().getName();
System.out.println (name + " entered A.foo");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println ("A interrupted");
}
System.out.println (name + " trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println ("Insied 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(InterruptedException e){
System.out.println ("B interrupted");
}
System.out.println (name + " trying to call A.last()");
a.last();
}
synchronized void last(){
System.out.println ("Inside B.last");
}
}class DeadLock implements Runnable{
A a = new A();
B b = new B();
DeadLock(){
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b);
System.out.println ("Back in main thread");
}
public void run(){
b.bar(a);
System.out.println ("Back in other thread");
}
public static void main(String[] args){
Thread.currentThread().setName("MainThread");
System.out.println ("当前线程:" + Thread.currentThread().getName());
new DeadLock();
}
}
synchronized void foo(B b){
String name = Thread.currentThread().getName();
System.out.println (name + " entered A.foo");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println ("A interrupted");
}
System.out.println (name + " trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println ("Insied 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(InterruptedException e){
System.out.println ("B interrupted");
}
System.out.println (name + " trying to call A.last()");
a.last();
}
synchronized void last(){
System.out.println ("Inside B.last");
}
}class DeadLock implements Runnable{
A a = new A();
B b = new B();
DeadLock(){
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b);
System.out.println ("Back in main thread");
}
public void run(){
b.bar(a);
System.out.println ("Back in other thread");
}
public static void main(String[] args){
Thread.currentThread().setName("MainThread");
System.out.println ("当前线程:" + Thread.currentThread().getName());
new DeadLock();
}
}
解决方案 »
- c的代码转成java的
- java 非法表达式的开始
- 关于JAVA开发桌面的一点小困扰
- 书上说date类对象要转换为字符串,才能将其输出。但是我直接输出对象同样可以呀
- SWING 难题难了我很久,我一个画面有很多,JLabel,JButton,JTable,等组建,当他们重合的时候,我要怎么控制控制他们谁显示在最上层,我现
- 关于在JAVA中绘画GIF动画文件的问题!非常的奇怪!!!
- 哪位网友遇到过这样的错误?
- 关于visualage的安装问题
- 在Jbuilder中如何根据条件从表格中取的唯一的记录?
- 请教:为何在Jbulider3中,程序无法找到com.sun.java.tree.* 类?
- 请教:谁能解释一下RTTI是什么啊,还有reflection
- 关于源代码中TAB字符的坏处
a.foo(b)--->取得a的锁,执行foo-->foo中执行b.last()->试图取得b的锁->waiting...
b.bar(a)--->取得b的锁,执行bar-->bar中执行a.last()->试图取得a的锁->waiting...