9、一个死锁的小例子

1、一个死锁的小例子

public class DeadLock {

	private String A = "a";
	private String B = "b";

	public static void main(String[] args) {

		new DeadLock().deadLock();

	}

	private void deadLock() {

		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (A) {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					// 注意是在synchronized (A)中,再去获取B资源
					synchronized (B) {
						System.out.println("线程T1");
					}

				}

			}
		});

		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (B) {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					// 注意是在synchronized (B)中,再去获取A资源
					synchronized (A) {
						System.out.println("线程T2");
					}

				}

			}
		});

		t1.start();
		t2.start();
	}
}


你可能感兴趣的:(多线程,死锁,JAVA死锁)