主线程:
public class DeadsynMain1 {
public static void main(String[] args) {
Service ser=new Service();
threadA tA=new threadA(ser);
tA.start();
threadB tB=new threadB(ser);
tB.start();
}
}
线程实现方法:
public class Service {
synchronized public void MethedA(){
System.out.println("A begin");
boolean iscountiueRun=true;
while(iscountiueRun){
}
System.out.println("A end");
}
Object object=new Object();
synchronized public void MethedB(){
//synchronized(object){
System.out.println("B begin");
System.out.println("B end");
//}
}
}
线程实例:
A线程:
public class threadA extends Thread{
private Service ser;
public threadA(Service ser) {
super();
this.ser=ser;
}
@Override
public void run() {
ser.MethedA();
}
}
B线程:
public class threadB extends Thread{
private Service ser;
public threadB(Service ser) {
super();
this.ser=ser;
}
@Override
public void run() {
ser.MethedB();
}
}
输出结果:A begin
分析原因:while循环进入无限期等待
解决办法:
1)去掉while循环
2)使用同步快,去掉注释部分
分析同步块:因为使用·object对象时同步快在等待上一个锁释放前可以访问非同步方法所以如果B方法也是syn的话那么也无法访问,但是只是对操作使用了syn所以可以访问
本文通过一个Java线程示例介绍了如何由于不当的同步方法调用导致死锁现象的发生,并提供了两种解决思路。

2830

被折叠的 条评论
为什么被折叠?



