当前位置: 移动技术网 > IT编程>开发语言>Java > java 死锁

java 死锁

2020年03月29日  | 移动技术网IT编程  | 我要评论

掐菜苔,电子爱好者,早产儿吃哪种奶粉好

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网