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

  }

  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值