Facebook
From Baby Meerkat, 7 Years ago, written in Java.
Embed
Download Paste or View Raw
Hits: 291
  1. import java.io.Reader;
  2. import java.util.*;
  3.  
  4. public class Relay implements Runnable {
  5.     boolean gotowy, koniec;
  6.     Reader aktualny;
  7.  
  8.     LinkedList<Thread> kolejka;
  9.     Map<Integer, Thread> mapa;
  10.  
  11.     public Relay(Reader reader) {
  12.         gotowy = false;
  13.         koniec = false;
  14.         aktualny = reader;
  15.         kolejka = new LinkedList<>();
  16.         mapa = new HashMap<>();
  17.         new Thread(this).start();
  18.     }
  19.  
  20.     public void register(int id, Thread competitor) {
  21.         mapa.put(id, competitor);
  22.     }
  23.  
  24.     public synchronized void startRelayRace() {
  25.         gotowy = true;
  26.     }
  27.  
  28.     public synchronized boolean dispatch() {
  29.         gotowy = true;
  30.         notifyAll();
  31.  
  32.         while (!gotowy || kolejka.peek() != Thread.currentThread()) {
  33.             try {
  34.                 if (koniec && kolejka.isEmpty()) {
  35.                     try {
  36.                         return false;
  37.                     } finally {
  38.                         notifyAll();
  39.                     }
  40.                 }
  41.                 wait();
  42.             }
  43.             catch (InterruptedException problem) {
  44.  
  45.             }
  46.         }
  47.         gotowy = false;
  48.         kolejka.poll();
  49.         return true;
  50.     }
  51.  
  52.     public void run() {
  53.         Scanner odczyt = new Scanner(aktualny);
  54.         while (odczyt.hasNextInt()) {
  55.             synchronized (this) {
  56.                 kolejka.offer(mapa.get(odczyt.nextInt()));
  57.                 notifyAll();
  58.             }
  59.             koniec = true;
  60.         }
  61.     }
  62. }