线程同步问题

Dabay 2006-12-13 04:13:27
class A{
public B b;

synchronized void methoda(){
String name = Thread.currentThread().getName();
System.out.println(name + " entered class A.methoda().");
try{
Thread.sleep(1000);
}catch(InterruptedException ie)
{
}
System.out.println(name + " trying to call B.methodb().");
b.methodb();
}

synchronized void methodb(){
System.out.println("Inside A.methodb().");
}
}

class B{
public A a;

synchronized void methoda(){
String name = Thread.currentThread().getName();
System.out.println(name + " entered class B.methoda().");
try{
Thread.sleep(1000);
}catch(InterruptedException ie)
{
}
System.out.println(name + " trying to call A.methodb().");
a.methodb();
}

synchronized void methodb(){
System.out.println("Inside B.methodb().");
}
}

class DeadLock implements Runnable{
A a;
B b;

DeadLock(){
a = new A();
b = new B();
a.b = b;
b.a = a;
Thread.currentThread().setName("MainThread");
new Thread(this).start();
a.methoda();
System.out.println("Over!");
}

public void run(){
Thread.currentThread().setName("RacingThread");
b.methoda();
System.out.println("Back from RacingThread.");
}

public static void main(String[] args){
new DeadLock();
}
}

为什么会出现死锁?2个线程分别调用methoda,然后交叉调用methodb,为什么会死锁呐? 请详细解答 谢谢!!
...全文
185 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dabay 2006-12-14
  • 打赏
  • 举报
回复
"一个类的某个synchronoized方法被lock后,这个类的其他synchronized方法也会被lock"

我当时也这么理解的,果然是这样! 谢谢!!1
88324877 2006-12-13
  • 打赏
  • 举报
回复
楼上的文字描述差不多就那意思
可以揭贴了
syoumei 2006-12-13
  • 打赏
  • 举报
回复
一个类的某个synchronoized方法被lock后,这个类的其他synchronized方法也会被lock

lz的例子 为什么会被death lock呢

是因为调用a.methoda的时候a.methodb也被lock,
当你b.methoda的时候b.methoddb也被lock

当a.methoda结束等待之后去调用b.methoddb的时候 b.methoddb是被锁住的(b.methoda执行中)
所以a等待。

当b.methoda结束等待之后去掉用a.methodb的时候a.methoda还在执行结束(a.methodb被锁)
所以b等待

然后大家都一起等死了

下面是我的测试代码

class B{

synchronized void methoda(){
System.out.println( " entered class B.methoda().");
try{
System.out.println("waitting for invoke methoda......(5s)");
Thread.sleep(5000);
}catch(InterruptedException ie)
{
}
System.out.println( " outed class B.methoda()");
}

synchronized void methodb(){
System.out.println("Inside B.methodb().");
}
}

public class DeadLock implements Runnable{
B b;

DeadLock(){
b = new B();
Thread.currentThread().setName("MainThread");
new Thread(this).start();
try{
System.out.println("waitting for invoke methodb......(1s)");
Thread.sleep(1000);
}catch(InterruptedException ie)
{
}
b.methodb();
System.out.println("Over!");
}

public void run(){
b.methoda();
}

public static void main(String[] args){
new DeadLock();
}
}
wangjichen_1 2006-12-13
  • 打赏
  • 举报
回复
确实是锁住了。
windproof 2006-12-13
  • 打赏
  • 举报
回复
期待真理!

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧