java deadlock analysis

1. Write seen cases of deadlock, run

package com.thread.thread.deadLock;


public class DeadLockTest {
	public static String objA = "strA";
	public static String objB = "strB";
	public static void main(String[] args){
		Thread a = new Thread(new Lock1());
		Thread b = new Thread(new Lock2());
		a.start();
		b.start();
	}
}
class Lock1 implements Runnable{
	@Override
	public void run(){
		try{
			System.out.println("Lock1 running");
			while(true){
				synchronized(DeadLockTest.objA){
					System.out.println("Lock1 lock strA");
					Thread.sleep (3000); // After obtaining strA hold for a moment, let Lock2 have enough time to lock strB
					synchronized(DeadLockTest.objB){
						System.out.println("Lock1 lock strB");
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace ();
		}
	}
}
class Lock2 implements Runnable{
	@Override
	public void run(){
		try{
			System.out.println("Lock2 running");
			while(true){
				synchronized(DeadLockTest.objB){
					System.out.println("Lock2 lock strB");
					Thread.sleep(3000);
					synchronized(DeadLockTest.objA){
						System.out.println("Lock2 lock strA");
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace ();
		}
	}
}

  2 jps -v find the corresponding thread (for the installation jvisualvm or jconsole can also view the deadlock stack information directly through the graphical interface)

  

 

 3jstack 7312 view deadlock information

 

 It can be seen thread-1 0x000000076f3b0308 locked and waiting 0x000000076f3b02f0 contrary thread-0

Guess you like

Origin www.cnblogs.com/deliciousFood/p/11652828.html