Advertisement
ahmad_zizo

Philosopher

May 25th, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package assignment3;
  7.  
  8. import java.util.Random;
  9.  
  10. /**
  11.  *
  12.  * @author Zizo
  13.  */
  14. public class Philosopher implements Runnable {
  15.  
  16.     private Random numGenerator = new Random();
  17.     private int id, meal;
  18.     private Monitor monitor;
  19.  
  20.     public Philosopher(int id, Monitor monitor, int meal) {
  21.         this.id = id;
  22.         this.monitor = monitor;
  23.         this.meal = meal;
  24.     }
  25.  
  26.     public void run() {
  27.         for (int j = 0; j < meal; j++) {
  28.             try {
  29.                 think();
  30.                 monitor.pickUp(id);
  31.                 eat();
  32.                 System.out.println("Philosopher " + id + " has done eating meal #" + meal + "\n");
  33.                 monitor.putDown(id);
  34.             } catch (InterruptedException e) {
  35.                 System.out.println("Philosopher " + id + " was interrupted.\n");
  36.             }
  37.         }
  38.     }
  39.  
  40.     private void think() throws InterruptedException {
  41.         System.out.println("Philosopher " + id + " is thinking.\n");
  42.         System.out.flush();
  43.         try {
  44.             Thread.sleep(numGenerator.nextInt(10));
  45.         } catch (InterruptedException e) {
  46.             e.printStackTrace();
  47.         }
  48.     }
  49.     private void eat() throws InterruptedException {
  50.         Thread.sleep(numGenerator.nextInt(10));
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement