Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package assignment3;
- import java.util.Random;
- /**
- *
- * @author Zizo
- */
- public class Philosopher implements Runnable {
- private Random numGenerator = new Random();
- private int id, meal;
- private Monitor monitor;
- public Philosopher(int id, Monitor monitor, int meal) {
- this.id = id;
- this.monitor = monitor;
- this.meal = meal;
- }
- public void run() {
- for (int j = 0; j < meal; j++) {
- try {
- think();
- monitor.pickUp(id);
- eat();
- System.out.println("Philosopher " + id + " has done eating meal #" + meal + "\n");
- monitor.putDown(id);
- } catch (InterruptedException e) {
- System.out.println("Philosopher " + id + " was interrupted.\n");
- }
- }
- }
- private void think() throws InterruptedException {
- System.out.println("Philosopher " + id + " is thinking.\n");
- System.out.flush();
- try {
- Thread.sleep(numGenerator.nextInt(10));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- private void eat() throws InterruptedException {
- Thread.sleep(numGenerator.nextInt(10));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement