1. 死锁
1.1 死锁的产生条件
1.1.1 互斥条件,即一个资源被一个线程访问时,另一个线程不能去访问。
1.1.2 不可抢占,即不可剥夺,资源请求者不能从占有者手中夺取资源,只能有持有者自己释放
1.1.3 请求和保持,即持有者也是请求者
1.1.4 循环等待,请求和持有资源形成一个环形。
1.2 Java中死锁一般发生在同步嵌套中,由于相互请求彼此持有的锁而发生死锁。如:
class one implements Runnable{
public void run(){
while(true){
synchronized(one.class)
{
synchronized(two.class)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...one");
}
}
}
}
}
class two implements Runnable{
public void run(){
while(true)
synchronized(two.class)
{
synchronized(one.class)
{
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...two");
}
}
}
}
}
public class DeadLock {
public static void main(String[] args) {
one o=new one();
two t=new two();
new Thread(o).start();
new Thread(t).start();
}
}
结果为:显示为死锁