Skip to content

Latest commit

 

History

History
60 lines (53 loc) · 1.12 KB

死锁.md

File metadata and controls

60 lines (53 loc) · 1.12 KB

死锁

/**
 * 死锁的原因就是同步的嵌套
 */
public class DeadLockTest {
	public static void main(String[] args) {
		Thread t1 = new Thread(new PrintRunnable(true));
		Thread t2 = new Thread(new PrintRunnable(false));
		t1.start();
		t2.start();
	}
}

class MyLock {
	static Object locka = new Object();
	static Object lockb = new Object();
}

class PrintRunnable implements Runnable {
	private boolean flag;

	PrintRunnable(boolean flag) {
		this.flag = flag;
	}

	public void run() {
		if (flag) {
			while (true) {
				synchronized (MyLock.locka) {
					System.out.println(Thread.currentThread().getName()
							+ "...if locka ");
					synchronized (MyLock.lockb) {
						System.out.println(Thread.currentThread().getName()
								+ "..if lockb");
					}
				}
			}
		} else {
			while (true) {
				synchronized (MyLock.lockb) {
					System.out.println(Thread.currentThread().getName()
							+ "..else lockb");
					synchronized (MyLock.locka) {
						System.out.println(Thread.currentThread().getName()
								+ ".....else locka");
					}
				}
			}
		}
	}
}