Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package kol2015g1;
- import java.util.Date;
- import java.util.HashSet;
- import java.util.concurrent.Semaphore;
- import problem.ProblemExecution;
- import problem.TemplateThread;
- /**
- *
- * @author ristes
- *
- */
- public class SchoolBusSolution {
- public static Semaphore blokirajStudentiVlez;
- public static Semaphore blokirajStudentiVlez1;
- public static Semaphore blokirajStudentIzlez;
- public static Semaphore blokirajVozac;
- public static Semaphore blokirajTrgvenje;
- public static Semaphore lock;
- public static Semaphore edinstvenVozac;
- public static int brojac;
- public static void init() {
- blokirajStudentiVlez = new Semaphore(0);
- blokirajStudentiVlez1 = new Semaphore(0);
- blokirajStudentIzlez = new Semaphore(0);
- blokirajVozac = new Semaphore(0);
- lock = new Semaphore(1);
- brojac = 0;
- edinstvenVozac = new Semaphore(1);
- blokirajTrgvenje = new Semaphore(0);
- }
- public static class Driver extends TemplateThread {
- public Driver(int numRuns) {
- super(numRuns);
- }
- @Override
- public void execute() throws InterruptedException {
- edinstvenVozac.acquire();
- lock.acquire();
- state.driverEnter();
- blokirajStudentiVlez.release(50);
- lock.release();
- blokirajTrgvenje.acquire();
- state.busDeparture();
- state.busArrive();
- blokirajStudentIzlez.release(50);
- blokirajVozac.acquire();
- state.driverLeave();
- edinstvenVozac.release();
- }
- }
- public static class Student extends TemplateThread {
- public Student(int numRuns) {
- super(numRuns);
- }
- @Override
- public void execute() throws InterruptedException {
- blokirajStudentiVlez.acquire();
- lock.acquire();
- brojac++;
- state.studentEnter();
- if (brojac == 50) {
- blokirajTrgvenje.release();
- }
- lock.release();
- blokirajStudentIzlez.acquire();
- lock.acquire();
- state.studentLeave();
- brojac--;
- if (brojac == 0){
- blokirajVozac.release();
- }
- lock.release();
- }
- }
- static SchoolBusState state = new SchoolBusState();
- public static void main(String[] args) {
- for (int i = 0; i < 10; i++) {
- run();
- }
- }
- public static void run() {
- try {
- int numRuns = 1;
- int numScenarios = 50;
- HashSet<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < numScenarios; i++) {
- Student p = new Student(numRuns);
- threads.add(p);
- if (i % 50 == 0) {
- Driver c = new Driver(numRuns);
- threads.add(c);
- }
- }
- init();
- ProblemExecution.start(threads, state);
- System.out.println(new Date().getTime());
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement