欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java 死锁,

来源: javaer 分享于  点击 36387 次 点评:88

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

 

相关文章

    暂无相关文章
相关栏目:

用户点评