死锁就是:
a线程 使用a锁 然后在使用b锁
b线程 使用b锁 然后在使用a锁
要是a线程执行到a锁的时候 想要调用b锁,而这时b线程执行b锁之后想要调用a锁,因为相互的锁都有在用,这就导致了相互等待锁用完的情况,然后因为锁又各自在用,是用不完的,这就导致了死锁。以下是代码示例:
主线程调用 testSS方法
private void testSS() {
Object a = new Object();
Object b = new Object();
MyCounter counter = new MyCounter(a, b);
AThread aThread = new AThread(counter);
BThread bThread = new BThread(counter);
aThread.start();
bThread.start();
}
class MyCounter {
Object lockA, lockB;
int n = 0;
int m = 0;
public MyCounter(Object lockA, Object lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
public void add() {
synchronized (lockB) {
int a = (int) (Math.random() * 10);
n += a;
System.out.println("add当前线程:" + Thread.currentThread());
synchronized (lockA) {
int aa = (int) (Math.random() * 10);
m += aa;
System.out.println("add当前线程:" + Thread.currentThread());
}
}
}
public void dec() {
synchronized (lockA) {
int a = (int) (Math.random() * 10);
n -= a;
System.out.println("dec当前线程:" + Thread.currentThread());
synchronized (lockB) {
int aa = (int) (Math.random() * 10);
m -= aa;
System.out.println("dec当前线程:" + Thread.currentThread());
}
}
}
}
class AThread extends Thread {
MyCounter c;
int n = 1000;
public AThread(MyCounter c) {
this.c = c;
}
@Override
public void run() {
// while (n > 0) {
c.add();
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
c.dec();
System.out.println("athread:" + c.m);
System.out.println("athread:" + c.n);
n--;
// }
}
}
class BThread extends Thread {
MyCounter c;
int n = 1000;
public BThread(MyCounter c) {
this.c = c;
}
@Override
public void run() {
// while (n > 0) {
c.dec();
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
c.add();
System.out.println("bthread:" + c.m);
System.out.println("bthread:" + c.n);
n--;
// }
}
}
执行结果: