package multiThread; /* * 死锁:死锁描述了这样一种情景,两个或多个线程永久阻塞,互相等待对方释放资源。 * 当DeadLock运行后,两个线程极有可能阻塞,当它们尝试调用bowBack方法时。 * 没有哪个阻塞会结束,因为每个线程都在等待另一个线程退出bow方法。 */ public class DeadLock { public static void main(String[] args){ final Person person1 = new DeadLock().new Person("jihaibo"); final Person person2 = new DeadLock().new Person("zhangxiaoyan"); Thread thread1 = new Thread(new Runnable(){ @Override public void run() { person1.bow(person2); /*while(true){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } person1.bow(person2); }*/ } }); Thread thread2 = new Thread(new Runnable(){ @Override public void run() { person2.bow(person1); /*while(true){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } person2.bow(person1); }*/ } }); thread1.start(); /*try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ thread2.start(); } class Person { String name; public Person(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public synchronized void bow(Person friend){ System.out.println(name + "给" + friend.getName() + "鞠躬"); friend.bowBack(this); } public synchronized void bowBack(Person friend){ System.out.println(friend.getName() + "给" + name + "回敬鞠躬"); } } }