1,关于死锁的理解
死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。
2,模拟死锁
背景介绍:我们创建一个朋友类,当朋友向我们鞠躬的时候,我们也要向朋友鞠躬,这样才算一个完整的动作。当两人
同时鞠躬的时候,都在等待对方鞠躬。这时就造成了死锁。
模拟程序:
package com.yxy.thread; /** * @author windows * 死锁模拟程序 */ public class Deadlock { /** * @author windows * 朋友实体类 */ static class Friend { //朋友名字 private final String name; //朋友实体类型的构造方法 public Friend(String name) { this.name = name; } //获取名字 public String getName() { return this.name; } //朋友向我鞠躬方法,(同步的) public synchronized void bow(Friend bower) { System.out.format("%s: %s" + " has bowed to me!%n", this.name, bower.getName()); bower.bowBack(this); } //我回敬鞠躬方法,(同步的) public synchronized void bowBack(Friend bower) { System.out.format("%s: %s" + " has bowed back to me!%n", this.name, bower.getName()); } } public static void main(String[] args) { //死锁模拟程序测试开始 //创建两个友人alphonse,Gaston final Friend alphonse = new Friend("Alphonse"); final Friend gaston = new Friend("Gaston"); //启动两位友人鞠躬的线程。 new Thread(new Runnable() { public void run() { alphonse.bow(gaston); } }).start(); new Thread(new Runnable() { public void run() { gaston.bow(alphonse); } }).start(); } }