java 死锁

class Ticket implements Runnable {
    private static int tick = 100;
    boolean flag = true;

    @Override
    public void run() {
        if (flag) {
            while (true) {
                synchronized (Integer.class) {
                    show();
                }
            }
        } else while (true)
            show();
    }

    public synchronized void show() {
        synchronized (Integer.class) {
            if (tick > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                }
                System.out.println(Thread.currentThread().getName() + "...show():" + tick--);
            }
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Ticket t = new Ticket();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {

        }
        t.flag = false;
        t2.start();
    }
}

同步中嵌套同步。

写一个死锁:

class Test implements Runnable {
    private boolean flag;

    Test(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            while (true) {
                synchronized (Object.class) {
                    System.out.println("if Object...");
                    synchronized (Integer.class) {
                        System.out.println("if Integer...");
                    }
                }
            }
        } else {
            while (true) {
                synchronized (Integer.class) {
                    System.out.println("else Integer...");
                    synchronized (Object.class) {
                        System.out.println("else Object...");
                    }
                }
            }
        }
    }
}

public class DeadLockDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Test(true));
        Thread thread2 = new Thread(new Test(false));
        thread1.start();
        thread2.start();
    }
}

 

posted @ 2020-03-28 21:18  hongxiao2020  阅读(202)  评论(0编辑  收藏  举报