b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

java多线程死锁 moira33的博客(4)

电脑杂谈  发布时间:2017-12-25 23:02:18  来源:网络整理
public class BankDemo {
    public static void main(String[] args) {
        Cus c = new Cus();
        new Thread(c).start();
        new Thread(c).start();
    }
}

同步中嵌套同步,用到不同的锁。

public class Test implements Runnable {
    private boolean flag;

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

    public void run() {
        if (flag) {
            while (true) {
                synchronized (MyLock.locka) {
                    System.out.println(Thread.currentThread().getName() + "...if locka ");
                    synchronized (MyLock.lockb) {
                        System.out.println(Thread.currentThread().getName() + "..if lockb");
                    }
                }
            }
        } else {
            while (true) {
                synchronized (MyLock.lockb) {
                    System.out.println(Thread.currentThread().getName() + "..else lockb");
                    synchronized (MyLock.locka) {
                        System.out.println(Thread.currentThread().getName() + ".....else locka");
                    }
                }
            }
        }
    }
}

class MyLock {
    static Object locka = new Object();
    static Object lockb = new Object();
}
class DeadLockTest {
    public static void main(String[] args) {
        /*      Thread t1 = new Thread(new Test(true));
                Thread t2 = new Thread(new Test(false));
                t1.start();
                t2.start();  */
        new Thread(new Test(true)).start();//匿名对象,对上面简化
        new Thread(new Test(false)).start();
    }
}


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-55883-4.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...