java线程死锁问题案列

public class DeadLock {
//线程死锁:双方占用对面资源,不退出,导致线程无法执行完成造成死锁 程序因此动不了
static StringBuffer sb1=new StringBuffer();
static StringBuffer sb2=new StringBuffer();
public static void main(String[] args) {
new Thread(){
public void run(){
synchronized(sb1){
sb1.append("a");
try {
Thread.currentThread().sleep(10);//线程sb1休息10毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(sb2){//此锁被下面线程抢到,暂时无法执行
sb2.append("b");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
new Thread(){
public void run(){
synchronized(sb2){//此线程抢锁
sb2.append("b");
synchronized(sb1){//sb1未执行完,进不来
sb1.append("a");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
}


}

你可能感兴趣的:(java线程死锁问题案列)