1700451309
1700451310
//Do Something
1700451311
1700451312
}
1700451313
1700451314
}
1700451315
1700451316
方法method1是synchronized修饰的,方法method2也是synchronized修饰的,method1调用method2是没有任何问题的,因为是同一个线程持有对象锁,在一个线程内多个synchronized方法重入完全是可行的,此种情况下不会产生死锁。
1700451317
1700451318
那什么情况下会产生死锁呢?看如下代码:
1700451319
1700451320
//资源A
1700451321
1700451322
static class A{
1700451323
1700451324
public synchronized void a1(B b){
1700451325
1700451326
String name=Thread.currentThread().getName();
1700451327
1700451328
System.out.println(name+“进入A.a1()”);
1700451329
1700451330
try{
1700451331
1700451332
//休眠1秒,仍然持有锁
1700451333
1700451334
Thread.sleep(1000);
1700451335
1700451336
}catch(Exception e){
1700451337
1700451338
//异常处理
1700451339
1700451340
}
1700451341
1700451342
System.out.println(name+“试图访问B.b2()”);
1700451343
1700451344
b.b2();
1700451345
1700451346
}
1700451347
1700451348
public synchronized void a2(){
1700451349
1700451350
System.out.println(“进入a.a2()”);
1700451351
1700451352
}
1700451353
1700451354
}
1700451355
1700451356
//资源B
1700451357
1700451358
static class B{
[
上一页 ]
[ :1.700451309e+09 ]
[
下一页 ]