A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© EarlyHeart 中级黑马   /  2014-7-9 20:55  /  754 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 EarlyHeart 于 2014-7-9 20:58 编辑
  1. public class Demo4 {
  2.         public static void main(String[] args) throws InterruptedException {
  3.                 EatFood e = new EatFood();
  4.                 Thread t1 = new Thread(e, "张三");
  5.                 Thread t2 = new Thread(e, "李四");
  6.                 t1.start();
  7.                 t2.start();
  8.         }

  9. }

  10. class EatFood implements Runnable {
  11.         Object o = new Object();
  12.         int food = 1000;

  13.         public void run() {
  14.                 while (true) {
  15.                         synchronized (this) {
  16.                                 //假设同时刻李四来到了这里
  17.                                 synchronized (o) {
  18.                                         if (food > 0)
  19.                                                 System.out.println(Thread.currentThread().getName()
  20.                                                                 + "抢到了第" + (food--) + "个food");
  21.                                         else
  22.                                                 return;

  23.                                 }
  24.                         }
  25.                         synchronized (o) {
  26.                                 //假设此时刻张三来到了这里
  27.                                 synchronized (this) {
  28.                                         if (food > 0)
  29.                                                 System.out.println(Thread.currentThread().getName()
  30.                                                                 + "抢到了第" + (food--) + "个food");
  31.                                         else
  32.                                                 return;
  33.                                 }
  34.                         }
  35.                 }
  36.         }
  37. }
复制代码

点评

问题呢?  发表于 2014-7-9 20:57

1 个回复

倒序浏览
您需要登录后才可以回帖 登录 | 加入黑马