java多线程之死锁的例子

在java多线程编写程序中特别害怕的一种情况就是死锁,他会让程序死在哪里不在继续执行下面就来看一个死锁的例子:


/**
 * 死锁的例子
 */
public class SiSuoTest {

    public static void main(String[] args) {
        LineTh ta1 = new LineTh(true);
        LineTh ta2 = new LineTh(false);
        Thread a = new Thread(ta1);
        a.setName("a");//给线程起名字为a
        Thread b = new Thread(ta2);
        b.setName("b");//给线程起名字为b

        a.start();
        b.start();
    }
}

class Luck {
    public final static Object obj1 = new Object();
    public final static Object obj2 = new Object();
}

class LineTh implements Runnable {
    private boolean flag = false;

    LineTh(boolean flage) {
        flag = flage;
    }
    public void run() {
        if (flag) {
            while (true) {
                synchronized (Luck.obj1) {
                    System.out.println("线程:"+Thread.currentThread().getName()+ "....  获取if 的 obj1");
                    synchronized (Luck.obj2) {
                        System.out.println("线程:"+Thread.currentThread().getName()   + "....  获取if 的 obj2");
                    }
                }
            }
        } else {
            while (true) {
                synchronized (Luck.obj2) {
                    System.out.println("线程:"+Thread.currentThread().getName()   + "....  获取else 的 obj2");
                    synchronized (Luck.obj1) {
                        System.out.println("线程:"+Thread.currentThread().getName()+ "....  获取else 的 obj1");
                    }
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_29428215/article/details/76090908