一、什么是死锁?
线程死锁是只两个或多个线程互相持有对方所需要的资源,导致这些线程处于等待状态,互相等待对方释放资源,如果线程都不主动释放锁占有资源,将会导致死锁。
二、产生死锁的原因?
1、系统资源不足;2、资源分配不当;3、进程推进顺序不合适
三、产生死锁的条件?
1、互斥条件:进程对于所分配到的资源具有排它性,一个资源只能被一个进程占用,直到该资源被进程释放;
2、请求和保持条件:一个进程因为请求被占用资源而发生阻塞时,对已获得的资源保持不放;
3、不可剥夺条件:任何一个资源在没被该进程释放前,其它任何进程都无法进行剥夺占用;
4、循环等待条件:当发生死锁时,所等待的进程必定会发生一个环路(类似死循环),造成永久阻塞。
四、解决死锁
解决死锁一般就是通过破坏产生死锁的条件来实现,
1、破坏互斥条件:一般这个无法实现;
2、破坏请求和保持条件:一次性获取所有资源;
3、破坏不可剥夺条件:加入定时机制;
4、破坏循环等待条件:按顺序获取资源。
五、java实现死锁demo
public class LockDemo {
public static String block1 = "block1";
public static String block2 = "block2";
public static void main(String []args){
Thread t1 = new Thread(new lock1());
Thread t2 = new Thread(new lock2());
t1.start();
t2.start();
}
}
class lock1 implements Runnable{
@Override
public void run() {
System.out.println("lock1 is running");
while(true){
synchronized (LockDemo.block1){
System.out.println("lock block1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} synchronized (LockDemo.block2){
System.out.println("lock block2");
}
}
}
class lock2 implements Runnable {
@Override
public void run() {
System.out.println("lock2 is running");
synchronized (LockDemo.block2){
System.out.println("lock block2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} synchronized (LockDemo.block1){
System.out.println("lock block1");
}
}
}
}
六、解决死锁demo
这里通过破坏循环等待条件,按顺序加锁(可以看到两个线程的加锁顺序是一样的)
public class LockDemo {
public static String block1 = "block1";
public static String block2 = "block2";
public static void main(String []args){
Thread t1 = new Thread(new lock1());
Thread t2 = new Thread(new lock2());
t1.start();
t2.start();
}
}
class lock1 implements Runnable{
@Override
public void run() {
System.out.println("lock1 is running");
while(true){
synchronized (LockDemo.block2){
System.out.println("lock block1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} synchronized (LockDemo.block1){
System.out.println("lock block2");
}
}
}
class lock2 implements Runnable {
@Override
public void run() {
System.out.println("lock2 is running");
synchronized (LockDemo.block2){
System.out.println("lock block2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} synchronized (LockDemo.block1){
System.out.println("lock block1");
}
}
}
}
网友评论