死锁的案例
public class TestSynchronized {public static void main(String args[]){DeadClock deadClock1 = new DeadClock(); DeadClock deadClock2 = new DeadClock(); deadClock1.flag = 1;deadClock2.flag = 2;new Thread(deadClock1).start();new Thread(deadClock2).start();}}class DeadClock implements Runnable{static Object o1 = new Object();static Object o2 = new Object();int flag = 0;public void run() {if(flag==1){synchronized(o1){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}synchronized(o2){System.out.println(1);}}}if(flag==2){synchronized(o2){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}synchronized(o1){System.out.println(2);}}}}}
页:
[1]