同步锁使用的弊端:当线程任务中出现了多个同步(多个锁)时,如果同步中嵌套了其他的同步。这时容易引发一种现象:程序出现无限等待,这种现象我们称为死锁。这种情况能避免就避免掉。
synchronzied(A锁){
synchronized(B锁){
}
}
我们进行下死锁情况的代码演示:
(1)定义锁对象类
public class MyLock {
public static final Object lockA = new Object();
public static final Object lockB = new Object();
}
(2)线程任务类
public class ThreadTask implements Runnable{
private int x = 0;
@Override
public void run() {
while (true) {
if (x%2==0) {
synchronized (MyLock .lockA) {
System.out.println(Thread.currentThread().getName()+"if lookA");
synchronized (MyLock .lockB ) {
System.out.println(Thread.currentThread().getName()+"if lookB ");
}
}
}else {
synchronized (MyLock .lockB) {
System.out.println(Thread.currentThread().getName()+"else lookB");
synchronized (MyLock .lockA) {
System.out.println(Thread.currentThread().getName()+"else lookA ");
}
}
}
x++;
}
}
}
(3)测试类
public class Tests {
public static void main(String[] args) {
ThreadTask tt1 = new ThreadTask();
Thread th = new Thread(tt1);
Thread th2 = new Thread(tt1);
th.start();
th2.start();
}
}