Advertisement
botvn

philosopher

Dec 20th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.99 KB | None | 0 0
  1. package DINING_PHILOSOPHER;
  2.  
  3. public class Philosopher extends Thread{
  4.     public static int Total=0;//tong so thread khoi tao
  5.     public static int runTotal=0;//tong so thread dang chay
  6.     private Chopstick left,right;
  7.     private String name;
  8.     public Philosopher(String name,Chopstick left,Chopstick right){
  9.         this.name=name;
  10.         this.left=left;
  11.         this.right=right;
  12.         Total++;
  13.     }
  14.    
  15.     public void eat(){
  16.         synchronized(left){
  17.             synchronized(right){
  18.                 left.use();
  19.                 right.use();
  20.                 System.out.println(name+" nhat dua");
  21.                 try {
  22.                     Thread.sleep(1000);
  23.                 } catch (InterruptedException e) {
  24.                 }
  25.             }
  26.         }
  27.         think();
  28.     }
  29.     public void think(){
  30.         System.out.println(name+" bo dua");
  31.         left.release();
  32.         right.release();
  33.         this.runTotal--;
  34.         try {
  35.             Thread.sleep(1000);
  36.         } catch (InterruptedException e) {
  37.         }
  38.     }
  39.     public void run(){
  40.         for(int i=1;i<=10;i++)
  41.         {
  42.             while(true){
  43.                 if((Total-runTotal)!=1){
  44.                     this.runTotal++;
  45.                     eat();
  46.                     break;
  47.                 }
  48.             }
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement