From a68fa3c3c96c38b811755022089cb8aee2f5521c Mon Sep 17 00:00:00 2001 From: Camil Staps Date: Fri, 29 May 2015 12:06:42 +0200 Subject: Intermediate commit: works partially, but sometimes cars go over each other (Crossing.isAllowed() is not synchronized) --- .../src/com/camilstaps/route66/Crossing.java | 61 ++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Week14 Route 66/src/com/camilstaps/route66/Crossing.java (limited to 'Week14 Route 66/src/com/camilstaps/route66/Crossing.java') diff --git a/Week14 Route 66/src/com/camilstaps/route66/Crossing.java b/Week14 Route 66/src/com/camilstaps/route66/Crossing.java new file mode 100644 index 0000000..eba5bfe --- /dev/null +++ b/Week14 Route 66/src/com/camilstaps/route66/Crossing.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2015 Camil Staps + */ +package com.camilstaps.route66; + +import OO14route66.Direction; +import OO14route66.Model; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author camilstaps + */ +public class Crossing { + + private final Model model; + private Direction allowed; + private boolean waiting = false; + private int requests = 0; + + public Crossing(Model model, Direction allowed) { + this.model = model; + this.allowed = allowed; + } + + public Direction getAllowed() { + return allowed; + } + + public synchronized void doSwitch() { + waiting = true; + while (!model.isNoCarsOnCrossing()); + System.err.println("Switching"); + if (allowed == Direction.East || allowed == Direction.West) { + allowed = Direction.North; + } else { + allowed = Direction.East; + } + requests = 0; + System.err.println("Switched to " + allowed); + waiting = false; + //notifyAll(); + } + + public boolean isAllowed(Direction direction) { + return !waiting && (direction == allowed || Direction.opposite(direction) == allowed); + } + + public boolean doRequest() { + //if (++requests >= 2) { + if (waiting) { + return false; + } + doSwitch(); + return true; + //} + //return false; + } + +} -- cgit v1.2.3