设为首页 加入收藏

TOP

java 线程死锁模拟
2014-11-24 01:42:56 来源: 作者: 【 】 浏览:0
Tags:java 线程 模拟

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();
    }
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Struts2 Action接口与ActionSuppo.. 下一篇Java知识点总结

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: