写了一个死锁的小例子;
死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。
public class TestDeadLock implements Runnable{
public int flag = 1;
static Object o1 = new Object(),o2 = new Object();
public void run(){
System.out.println("flag"+flag);
if(flag == 1){
synchronized (o1){
try {
Thread.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (o2){
System.out.println("111");
}
}
}
if (flag == 0){
synchronized (o2){
try {
Thread.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (o1){
System.out.println("000");
}
}
}
}
public static void main(String args[]){
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}