多线程中死锁产生的原因:在同步代码中嵌套同步,导致多线程访问的时候,锁无法被释放,产生思索。
举例代码:
package com.dss.test;
class ThreadTran1 implements Runnable{
private static int total = 100;
public boolean flag = true;
public Object object = new Object();
@Override
public void run() {
if(flag) {
while(true) {
synchronized (object) {
sale();
}
}
}else {
while(true) {
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
sale();
}
}
}
public synchronized void sale() {
synchronized (this) {
if(total > 0) {
System.out.println(Thread.currentThread().getName() + "出售第 " + (100-total+1) + "张票");
total--;
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
ThreadTran1 threadTran1 = new ThreadTran1();
Thread t1 = new Thread(threadTran1,"线程1");
Thread t2 = new Thread(threadTran1,"线程2");
t1.start();
try {
Thread.sleep(400);
}catch(Exception e) {
}
threadTran1.flag = false;
t2.start();
}
}
说明:
线程一启动之后,要先拿到 object 这个对象锁,之后要进入 sale() 方法,此时又要拿到 this 锁
而线程二启动之后,先进入 sale() 方法,先要拿到 this 锁,之后在 sale() 方法里面,有同步代码块,此时又要再拿 object 对象锁
当线程一先拿到 object 锁,线程二 先拿到 this 锁,此时线程一要再获取 this 锁,线程二要再获取 object 锁,但是都获取不到了,所以他们只能等锁被释放,但是锁永远不会被释放,这样,死锁就产生了