Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mk.ukim.finki.os.synchronization.exam14.june;
- import mk.ukim.finki.os.synchronization.ProblemExecution;
- import mk.ukim.finki.os.synchronization.TemplateThread;
- import java.util.Date;
- import java.util.HashSet;
- import java.util.concurrent.RejectedExecutionException;
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class Euro2016 {
- static Semaphore semA, semB;
- static Semaphore semDojdA, semDojdB;
- static Semaphore semBoard;
- static Semaphore semReady;
- static Semaphore semDone;
- static Semaphore semNext;
- static int a, b;
- static Lock lock = new ReentrantLock();
- public static void init() {
- semA = new Semaphore(4);
- semB = new Semaphore(4);
- semDojdA = new Semaphore(0);
- semDojdB = new Semaphore(0);
- semBoard = new Semaphore(0);
- semReady = new Semaphore(4);
- semDone = new Semaphore(0);
- semNext = new Semaphore(0);
- a = b = 0;
- }
- static class FanA extends TemplateThread {
- public FanA(int numRuns) {
- super(numRuns);
- }
- public void execute() throws InterruptedException {
- while(true){
- lock.lock();
- boolean mestoZaB = ( b==3 || (a==2 && b==1));
- if(!mestoZaB)
- {
- //semA.acquire();
- a++;
- state.board();
- if(a+b==4)
- {
- state.departure();
- a=b=0;
- }
- break;
- }
- lock.unlock();
- }
- lock.unlock();
- }
- }
- static class FanB extends TemplateThread {
- public FanB(int numRuns) {
- super(numRuns);
- }
- public void execute() throws InterruptedException {
- while(true){
- lock.lock();
- boolean mestoZaA = ( a==3 || (a==1 && b==2));
- if(!mestoZaA)
- {
- //semB.acquire();
- b++;
- state.board();
- if(a+b==4)
- {
- state.departure();
- a=b=0;
- }
- break;
- }
- lock.unlock();
- }
- lock.unlock();
- }
- }
- static Euro2016State state = new Euro2016State();
- public static void main(String[] args) {
- for (int i = 0; i < 15; i++)
- run();
- }
- public static void run() {
- try {
- int numRuns = 1;
- int numIterations = 120;
- HashSet<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < numIterations; i++) {
- FanA h = new FanA(numRuns);
- FanB s = new FanB(numRuns);
- threads.add(h);
- threads.add(s);
- }
- 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