1. 程式人生 > >Java一個簡單的死鎖例子

Java一個簡單的死鎖例子

內容:一個簡單的死鎖例子,大概的思路:兩個執行緒A和B,兩把鎖X和Y,現在A先拿到鎖X,然後sleep()一段時間,我們知道sleep()是不會釋放鎖資源的。然後如果這段時間執行緒B拿到鎖Y,也sleep()一段時間的話,那麼等到兩個執行緒都醒過來的話,那麼將互相等待對方釋放鎖資源而僵持下去,陷入死鎖。flag的作用就是讓A和B獲得不同的鎖。

public class TestDeadLock {
	
	public void run() {
		MyThread mt = new MyThread();
		new Thread(mt, "張三").start();
		new Thread(mt, "李四").start();
	}
	
	class MyThread implements Runnable {
		private Object o1 = new Object();
		private Object o2 = new Object();
		private boolean flag = true;
		

		@Override
		public void run() {
			if (flag) {
				flag = false;
				synchronized (o1) {
					System.out.println(Thread.currentThread().getName() + " have o1");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (o2) {
						System.out.println(Thread.currentThread().getName() + " have o2");
					}
				}
			} else {
				flag = true;
				synchronized (o2) {
					System.out.println(Thread.currentThread().getName() + " have o2");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (o1) {
						System.out.println(Thread.currentThread().getName() + " have o1");
					}
				}
			}
		}
	}
	
	public static void main(String[] args) {
		new TestDeadLock().run();
	}
}