突然被问到这个,概念呢都知道:
A需要等待B所拥有得资源才继续运行,B也一样,导致线程一直处于等待状态,而出现死锁现象。
条件:
互斥条件:一个资源只能由一个使用者占用
请求和保持条件:保持现有的资源,又请求新的资源
不剥夺条件:已被占用得资源,在未使用完前不能被剥夺
环路等待条件:a需要b,b需要c,c需要a,形成环路
package pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestLock {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
pool.submit(new LockThread(1));
pool.submit(new LockThread(2));
}
}
package pool;
public class LockThread implements Runnable{
private int i = 0;
private static Object f1 = new Object();
private static Object f2 = new Object();
public LockThread(int i) {
this.i = i;
}
@Override
public void run() {
if(i == 1){
synchronized (f1) {
System.out.println("1号线程,获取f1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (f2) {
System.out.println("1号线程,获取f2");
}
}
}
if(i == 2){
synchronized (f2) {
System.out.println("2号线程,获取f2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (f1) {
System.out.println("2号线程,获取f1");
}
}
}
}
}
运行结果:两个线程处于无线等待过程