儿童节,托儿所。

package ym.com.yjc;

/**

  • 此类用于演示死锁 A B 俩各类 分别有一个 money 属性 如果 A 增加 100 则 b 减 100 相反 b+100 a-100
    */
    public class TestLock {
    public static void main(String[] args) {
    A a = new A();
    B b = new B();
    DeadLockDemo deadLockDemo = new DeadLockDemo(a, b, true);
    deadLockDemo.start();
    DeadLockDemo deadLockDemo1 = new DeadLockDemo(a, b, false);
    deadLockDemo1.start();

    }

}

class DeadLockDemo extends Thread {
A a;
B b;

public DeadLockDemo(A a, B b, boolean flag) {
    this.a = a;
    this.b = b;
    this.flag = flag;
}

boolean flag;


@Override
public void run() {
    if (flag) {
        synchronized (a) {
            a.save();
            synchronized (b) {
                b.minus();

            }
        }


    } else {
        synchronized (b) {
            b.save();
            synchronized (a) {
                a.minus();

            }
        }
    }
}

}

class A {
public int a;

public void save() {

    a = a + 100;
    System.out.println("a=" + a);
}

public void minus() {
    a = a - 100;
    System.out.println("a=" + a);
}

}

class B {
public int b;

public void save() {

    b = b + 100;
    System.out.println("b=" + b);
}

public void minus() {
    System.out.println("b=" + b);
    b = b - 100;
}

}

你可能感兴趣的:(儿童节,托儿所。)