DeadLock Example

start


public class DeadLock {
    private static Object lockA = new Object();
    private static Object lockB = new Object();
    private static void startA() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                String name=Thread.currentThread().getName();
                System.out.println(name+" is running!!");
                synchronized (lockA) {
                    System.out.println(name+" got lockA");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    synchronized (lockB) {
                        System.out.println(name+" got lockB");
                    }
                }
            }
        },"ThreadA").start();

    }

    private static void startB() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                String name=Thread.currentThread().getName();
                // TODO Auto-generated method stub
                System.out.println(name+" is running!!");
                synchronized (lockB) {
                    System.out.println(name+" got lockB");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    synchronized (lockA) {
                        System.out.println(name+" got lockA");
                    }
                }
            }
        },"Thread B").start();
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        startA();
        startB();
    }
}

end

你可能感兴趣的:(DeadLock Example)