Deal Lock
两个线程互相占有对方需要的资源而不释放,便形成了死锁。
造成死锁的条件
产生死锁的四个必要条件:
互斥条件:所谓互斥就是进程在某一时间内独占资源。
请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
不剥夺条件:进程已获得资源,在末使用完之前,不能强行剥夺。
循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
只要解除上述的一个条件就能解除死锁和避免死锁。
实例代码
public class DeadThread{
public static void main(String[] args) {
final Lock lock1=new ReentrantLock();
final Lock lock2=new ReentrantLock();
Thread thread1=new Thread(){
@Override
public void run() {
method(lock1,lock2);
}
};
Thread thread2=new Thread(){
@Override
public void run() {
method(lock2,lock1);
}
};
thread1.start();
thread2.start();
System.out.println("start interrupt...");
thread1.interrupt();
thread2.interrupt();
System.out.println("stop interrupt....");
}
public static void method(Lock lock1,Lock lock2) {
try {
lock1.lock();
System.out.println("lock1.lock...");
long starttime = System.currentTimeMillis();
while (System.currentTimeMillis() - starttime < 1000) {
}
lock2.lock();
System.out.println("lock2.lock");
}finally {
lock1.unlock();
lock2.unlock();
}
}
}
运行结果: