Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1606123
  • 博文数量: 695
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4027
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-20 21:22
文章分类

全部博文(695)

文章存档

2018年(18)

2017年(74)

2016年(170)

2015年(102)

2014年(276)

2013年(55)

分类: Java

2017-01-19 15:12:26


点击(此处)折叠或打开

  1. /**
  2.  * All rights Reserved, Designed By travelsky
  3.  * @Title: Philosopher.java
  4.  * @Package com.slg.dinner
  5.  * @Description: TODO(用一句话描述该文件做什么)
  6.  * @author: slg
  7.  * @date: 2017年1月19日 下午2:02:41
  8.  * @version V1.0
  9.  * @Copyright: 2017 travelsky. All rights reserved.
  10.  * 注意:本内容仅限航信内部传阅,禁止外泄以及用于其他的商业目
  11.  */
  12. package com.slg.dinner;

  13. import java.util.Random;
  14. import java.util.concurrent.locks.Lock;
  15. import java.util.concurrent.locks.ReentrantLock;

  16. /**
  17.  * @author slg
  18.  *
  19.  */
  20. public class Philosopher implements Runnable{
  21.     static final int COUNT = 5;
  22.     static Lock[] chopsticks = new Lock[COUNT];    
  23.     static {
  24.         for(int i=0;i<COUNT;i++){
  25.             chopsticks[i] = new ReentrantLock();
  26.         }
  27.     }
  28.     private String name;
  29.     private int id;
  30.     public Philosopher(String name,int id){
  31.         this.name = name;
  32.         this.id = id;
  33.     }
  34.     void eat(){
  35.         while(true){
  36.             if(chopsticks[this.id].tryLock()){                
  37.                 if(chopsticks[(this.id+1)%COUNT].tryLock()){
  38.                     System.out.println(this.name+"is eat");
  39.                     chopsticks[(this.id+1)%COUNT].unlock();
  40.                     chopsticks[this.id].unlock();
  41.                     break;
  42.                             
  43.                 }else{
  44.                     try {
  45.                         Thread.sleep(new Random().nextInt(1000));
  46.                     } catch (InterruptedException e) {
  47.                         // TODO Auto-generated catch block
  48.                         e.printStackTrace();
  49.                     }finally{
  50.                         chopsticks[this.id].unlock();
  51.                     }
  52.                 }
  53.             }
  54.         }
  55.         
  56.     }
  57.     /* (non-Javadoc)
  58.      * @see java.lang.Runnable#run()
  59.      */
  60.     @Override
  61.     public void run() {
  62.          eat();        
  63.     }
  64.     public static void main(String []args){
  65.         
  66.         for(int i=0;i<COUNT;i++){
  67.             new Thread(new Philosopher("p"+i,i)).start();
  68.         }
  69.     }
  70. }

阅读(800) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~