2015-10-22 2 views
0

Я пытаюсь сделать программу, которая имитирует линию ожидания и подъем, и отдельных лыжников. Теперь мой выход прекрасен и, как ожидалось, пока лыжники не ударятся о верхнюю часть лифта, а затем начните кататься на лыжах, то есть когда начнутся нитки. Моя проблема в том, что после того, как лыжник закончил, он должен снова вернуться в очередь ожидания, но многие из лыжников пропали без вести и никогда не вернутся к линии.Данные, исчезающие при переходе на другую тему

Любые идеи?

import java.util.Random; 
import java.util.concurrent.BlockingQueue; 
import java.util.concurrent.LinkedBlockingQueue; 



public class ThreadsAssignment { 

    // Declare and initalise queues and arrays 
    public static BlockingQueue<String> liftQueue = new LinkedBlockingQueue<String>(11); 
    public static BlockingQueue<String> waitQueue = new LinkedBlockingQueue<String>(); 
    public static String toLift; 
    public static String toWait; 
    public static String liftFront = "EMPTY"; 
    public static String waitFront; 
    public static int populatedLift = 0; 
    public static int pauseLift; 
    public static int slopeTime; 
    public static String toPend; 
    public static int queueSize; 




    public static void main(String[] args) throws Exception{ 


     // fill both queues list for startup 
     for(int i = 0; i < 30; i++){ 
      waitQueue.add(Integer.toString(i)); 
     }  
     for(int j = 0; j < 10; j++){ 
      liftQueue.add("EMPTY"); 
     } 

     // loop the simulation 
     while(true){ 

      System.out.println("In Queue " + "(" + waitQueue.size() + "): " + waitQueue); 
      System.out.println("On Lift " + "(" + populatedLift + "): " + liftQueue + "\n"); 

      // Stop lift for 1 second 
      try{ 
       Thread.sleep(1000);} 
      catch (InterruptedException ex) {} 

      // test if the lift stops 
      if ((Math.random() * 100) >= 95) { 
       Random rand = new Random(); 
       pauseLift = rand.nextInt(8001); 

       System.out.println("Lift paused for " + pauseLift + " milliseconds"); 

       try{Thread.sleep(pauseLift);} 
       catch (InterruptedException ex){}} 
      else{} 




      // get the head of the waiting line then add it to lift, check if any skier is waiting. 
      liftFront = liftQueue.peek(); 

      if (waitQueue.size() == 0){ 
       liftQueue.add("EMPTY"); 
      } 
      else{ 
       toLift = waitQueue.take(); 
       liftQueue.add(toLift); 
       populatedLift++; 
      } 

      // if the front of the liftQueue is occupied, call a new skier thread 
      if (liftFront.equals("EMPTY")){ 
       liftQueue.poll();} 
      else{ 
       liftQueue.poll(); 
       populatedLift--; 
       skier s = new skier(liftFront, waitQueue); 
       new Thread(s).start(); 
      } 


     } 
    } 

    // skier thread   
    public static class skier extends Thread { 
     static String name; 
     static BlockingQueue<String> theQueue; 

     // Constructor for the thread 
     public skier(String name, BlockingQueue<String> theQueue){ 
      skier.name = name; 
      skier.theQueue = theQueue; 

     } 

     // run method that makes random skiing time then pends the skier back into the queue 
     @Override public void run() { 
      toPend = skier.name; 
      Random speed = new Random(); 
      slopeTime = speed.nextInt(10001) + 2000; 


      try {Thread.sleep(slopeTime);} 
      catch (InterruptedException ex){} 

      currentThread. 
      if (waitQueue.contains(toPend)){} 
      else {try { 
       waitQueue.put(toPend); 
      } catch (InterruptedException e){} 
      System.out.println(toPend + "has been pended");} 
     } 
    } 
} 

ответ

0

После кода может привести к лыжники стать отсутствующим:

static String name; 
static BlockingQueue<String> theQueue; 

static означает, что все экземпляры skier разделят последнее представленное имя. Вы должны сделать все лыжники держать их имена себе:

final String name; 
final BlockingQueue<String> theQueue; // this may be left `static` since there's only one instance, but this would be unclean code. 
// Or, as an option, let `skier` instances re-use outer class `queue`. 

Btw, Java имеет условность начиная имена классов с прописной буквы, поэтому она должна быть Skier, а также.

И вам не нужно EMPTY константу, просто вызовите queue.isEmpty()

Смежные вопросы