本帖最后由 nyk 于 2014-10-23 22:04 编辑
- public class DeadLockTest {
- public static void main(String[] args) {
- new Thread(new Test(true)).start();
- new Thread(new Test(false)).start();
- }
- }
- class Test implements Runnable {
- private boolean flag;
- Test(boolean flag) {
- this.flag = flag;
- }
- public void run(){
- if(flag){
- synchronized(MyLock.locka){
- System.out.println("if locka");
- synchronized(MyLock.lockb){
- System.out.println("if lockb");
- }
- }
- }
- else{
- synchronized(MyLock.lockb){
- System.out.println("else lockb");
- synchronized(MyLock.locka){
- System.out.println("else locka");
- }
- }
- }
- }
- }
- class MyLock{
- public static Object locka = new Object();
- public static Object lockb = new Object();
- }
复制代码
毕老师经典的死锁代码,结果是这样的
- if locka
- if lockb
- else lockb
- else locka
复制代码
想不通为什么锁住了,不是输一个if,输一个else才锁吗? |