码迷,mamicode.com
首页 > 编程语言 > 详细

java 死锁

时间:2020-03-28 21:44:19      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:死锁   syn   lag   int   private   interrupt   test   tick   rup   

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();
    }
}

 

java 死锁

标签:死锁   syn   lag   int   private   interrupt   test   tick   rup   

原文地址:https://www.cnblogs.com/hongxiao2020/p/12589455.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!