Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package lab4;
- import java.util.concurrent.Semaphore;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author k3liang
- */
- public class Philosphers implements Runnable {
- private static final long startTime= System.currentTimeMillis();
- public static final int MAX_ITERATIONS=3;
- private State state;
- private int philID;
- private static int nextID=1;
- public Semaphore semaphore;
- public static Semaphore semaphore2;
- public Philosphers Left;
- public Philosphers Right;
- public Philosphers()
- {
- philID=nextID++;
- semaphore= new Semaphore(0,true);
- semaphore2= new Semaphore(1,true);
- }
- @Override
- public void run() {
- System.out.println("STARTING #" + philID);
- for (int i = 0; i < MAX_ITERATIONS; i++) {
- state = State.THINKING;
- displayState();
- sleepAndDisplay();
- try {
- getFork();
- } catch (InterruptedException ex) {
- Logger.getLogger(Philosphers.class.getName()).log(Level.SEVERE, null, ex);
- }
- // state = State.HUNGRY;
- sleepAndDisplay();
- // state = State.EATING;
- sleepAndDisplay();
- try{
- putFork();
- } catch (InterruptedException ex) {
- Logger.getLogger(Philosphers.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- private void sleepAndDisplay() {
- try {
- Thread.sleep(0, (int) (1000000 * Math.random()));
- } catch (InterruptedException ex) {
- }
- displayState();
- }
- private void displayState() {
- long timeNow = System.currentTimeMillis() - startTime;
- System.out.println("Philosoper #" + philID + ": "
- + state + " time: " + timeNow + "ms");
- }
- private void getFork() throws InterruptedException
- {
- state = State.HUNGRY;
- while ( state == State.HUNGRY )
- {
- semaphore.acquire();
- if ( state == State.HUNGRY && Left.state != State.EATING && Right.state != State.EATING )
- {
- state = State.EATING;
- semaphore2.release();
- }
- semaphore.release();
- semaphore2.acquire();
- }
- }
- private void putFork() throws InterruptedException
- {
- semaphore.acquire();
- state= State.THINKING;
- if ( Left.state == State.HUNGRY)
- semaphore2.release();
- if ( Right.state == State.HUNGRY)
- semaphore2.release();
- semaphore.release();
- }
- }
Add Comment
Please, Sign In to add comment