java线程的死锁

原文链接

public class DeadLock implements Runnable {
	private boolean flag;
	static Object o1 = new Object(), o2 = new Object();

	public void run() {
		System.out.println(flag);
		if (flag) {
			synchronized (o1) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (o2) {
					System.out.println("AAA");
				}
			}
		} else {
			synchronized (o2) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (o1) {
					System.out.println("BBB");
				}
			}
		}
	}

	public static void main(String[] args) {
		DeadLock aaa = new DeadLock();
		DeadLock bbb = new DeadLock();
		aaa.flag = true;
		bbb.flag = false;
		Thread thA = new Thread(aaa);
		Thread thB = new Thread(bbb);
		thA.start();
		thB.start();
	}
}




你可能感兴趣的:(java,thread,html,Blog)