public synchronized void dispose() {
    List<SchedulerListener> l = listeners;
    listeners = null;

    if (l != null) {
      boolean cont = true;
      while (cont) {
        synchronized (l) {
          int queueSize = getQueueSize();
          if (queueSize == 0) {
            cont = false;
          } else {
            try {
              l.wait();
            } catch (InterruptedException ex) {
              // Ignore!
            }
          }
        }
      }

      synchronized (l) {
        l.clear();
      }
    }
  }
Пример #2
1
  public void run() {

    while (remainingJobs() > 0) {

      Object input = null;

      synchronized (pool) {
        while (pool.isEmpty()) {
          if (remainingJobs() == 0) {
            return;
          }
          try {
            pool.wait();
          } catch (InterruptedException e) {
          }
        }

        input = pool.remove(pool.size() - 1);

        process(input);
        jobsDone++;
      }
      // end if
    }
    // end while
  }
Пример #3
1
  public List<DiscoverableDevice> getDiscoverableSensor() {
    List<DiscoverableDevice> deviceList = null;

    // Reinit the USB (if needed), then ask for a list of devices
    if (!usbInited) initUSB();

    // If we have an a3pSession, try to get a device list from the ADK board
    if (a3pSession != null && !a3pSession.isClosed()) {
      deviceIDs.clear();

      Log.d(TAG, "Sending enumerate sensors req");

      int retries = 0;
      while (deviceIDs.size() == 0 && (retries < MAX_RETRIES_FOR_DISCOVERY)) {
        sendDeviceListRequest();
        retries++;
        if (DEBUG_VERBOSE) Log.d(TAG, "blocking for notify. retry cnt: " + retries);
        synchronized (deviceIDs) {
          try {
            deviceIDs.wait(2000);
            Log.d(TAG, "woke up with " + deviceIDs.size());
          } catch (InterruptedException iex) {
            iex.printStackTrace();
          }
        }
      }

      if (deviceIDs.size() == 0) {
        Log.e(TAG, "Finding deviceIDs failed!");
        Log.d(TAG, "<--- Exiting getDiscoverableSensor()");
        return null;
      }

      Log.d(TAG, "Finding deviceIDs succeeded!");

      deviceList = new ArrayList<DiscoverableDevice>();
      Iterator<String> deviceListIterator = deviceIDs.iterator();
      while (deviceListIterator.hasNext()) {
        String sensorID = deviceListIterator.next();
        USBDiscoverableDevice newDiscoverableDevice =
            new USBDiscoverableDevice(sensorID, this.mSensorManager);
        newDiscoverableDevice.connectionLost = false;
        deviceList.add(newDiscoverableDevice);

        Log.d(TAG, "updating sensor state in sensormanager");
        mSensorManager.updateSensorState(sensorID, DetailedSensorState.CONNECTED);
        Log.d(TAG, "sensorID " + sensorID + " set to connected in DB");
      }

      this.mDiscoverableDeviceList.clear();
      this.mDiscoverableDeviceList.addAll(deviceList);

      Log.d(TAG, deviceList.size() + " sensors found");
    } else {
      Log.d(TAG, "a3pSession is null or closed. cannot discover sensors ");
    }

    Log.d(TAG, "<--- Exiting getDiscoverableSensor()");
    return deviceList;
  }
Пример #4
1
 public void assertQueueChanges(int expectedEventCount) throws InterruptedException {
   synchronized (queueEvents) {
     while (queueEvents.size() < expectedEventCount) {
       queueEvents.wait(timeout);
     }
   }
 }
Пример #5
1
  private void waitForGlobalSuccessOrFailure() throws IOException {
    boolean wasInterrupted = false;

    try {
      synchronized (channels) {
        while ((globalSuccessCounter == 0) && (globalFailedCounter == 0)) {
          if (shutdown) {
            throw new IOException("The connection is being shutdown");
          }

          try {
            channels.wait();
          } catch (InterruptedException ignore) {
            wasInterrupted = true;
          }
        }

        if (globalFailedCounter != 0) {
          throw new IOException("The server denied the request (did you enable port forwarding?)");
        }

        if (globalSuccessCounter == 0) {
          throw new IOException("Illegal state.");
        }
      }
    } finally {
      if (wasInterrupted) Thread.currentThread().interrupt();
    }
  }
Пример #6
1
  private List<Status> fetchPreviousThreadNextStatus() throws TechnicalException {
    outln("waiting for previous thread to either provide data and/or be done");
    List<Status> previousStatusList = this.previousQueryThread.getChangedStatusList();
    List<Status> tmp = null;
    Status firstStatus = null;

    // Obtain lock on previous status
    synchronized (previousStatusList) {
      while (previousStatusList.isEmpty()) {
        try {
          previousStatusList.wait();
        } catch (InterruptedException e) {
          throw new TechnicalException(e);
        }
      }
      if (!previousStatusList.isEmpty()) {
        firstStatus =
            previousStatusList.remove(0); // remove status from list, it will then be processed
      } else {
        MyUtils.errorProgram("SPONTANEOUS NOTIFICATION!!!!!!!!"); // shouldn't happen really						
      }
      if (QueryRunnerPrototypeConstants.CHECK) tmp = new ArrayList<Status>(previousStatusList);
    }
    outln("previous status to process: " + firstStatus);

    return tmp;
  }
Пример #7
0
  @Override
  public void free(ResourceUser resourceUser, Set<TCSResource> resources) {
    Objects.requireNonNull(resourceUser, "resourceUser is null");
    Objects.requireNonNull(resources, "resources is null");

    synchronized (inquiringTasks) {
      boolean freeSuccessful = false;
      // Loop until we could free the resources.
      do {
        if (releasable) {
          log.fine("releasable flag set, releasing resources...");
          Set<TCSResource> freeableResources = getFreeableResources(resources, resourceUser);
          // Decrement the reservation counter for freed resources.
          log.fine("Releasing resources: " + freeableResources);
          for (TCSResource curRes : freeableResources) {
            getReservationEntry(curRes).free();
          }
          checkWaitingRequests();
          freeSuccessful = true;
        } else {
          log.fine("releasable flag not set, waiting...");
          try {
            inquiringTasks.wait();
            log.fine("Woken up, trying again...");
          } catch (InterruptedException exc) {
            throw new IllegalStateException("Unexpectedly interrupted", exc);
          }
        }
      } while (!freeSuccessful);
    }
  }
Пример #8
0
  @Ignore
  @Test
  public void testGetHistoryBarsFromDukascopyServer() throws InterruptedException {

    String start = "2011.01.01 00:00:00 +0000";
    String end = "2011.01.02 01:00:00 +0000";
    historyMarketDataFeedTestStrategy.setServerBars(kBarsFromDukascopyServer);
    historyMarketDataFeedTestStrategy.setTestBar_start(start);
    historyMarketDataFeedTestStrategy.setTestBar_end(end);
    historyMarketDataFeedTestStrategy.setTestPeriod(Period.TEN_SECS);
    historyMarketDataFeedTestStrategy.setInstrument(Instrument.EURUSD);

    dukascopyHistoryMarketDataFeedClient.setStrategy(historyMarketDataFeedTestStrategy);
    new Thread() {
      public void run() {
        dukascopyHistoryMarketDataFeedClient.start();
      }
    }.start();

    synchronized (kBarsFromDukascopyServer) {
      kBarsFromDukascopyServer.wait();
      logger.info("verify the data in kBarsFromDukascopyServer");
      logger.info("kBarsFromDukascopyServer size is " + kBarsFromDukascopyServer.size());
      for (HistoryDataKBar kbar : kBarsFromDukascopyServer) {
        logger.info(kbar.toString());
      }
    }
  }
Пример #9
0
 public List<Pointer> EnumWindows() {
   final List<Pointer> mutex = Collections.synchronizedList(new LinkedList<Pointer>());
   Thread enumThread =
       new Thread(
           new Runnable() {
             @Override
             public void run() {
               u32.EnumWindows(
                   new WNDENUMPROC() {
                     public boolean callback(Pointer hWnd, Pointer userData) {
                       mutex.add(hWnd);
                       return true;
                     }
                   },
                   null);
             }
           });
   enumThread.start();
   try {
     synchronized (mutex) {
       mutex.wait(20); // FIXME Find better method. Dont go below 10!
       enumThread.interrupt();
     }
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   return mutex;
 }
Пример #10
0
    @Override
    public void run() {
      while (true) {
        synchronized (shareData) {
          while (shareData.isEmpty()) {
            try {
              System.out.println(Thread.currentThread().getName() + " 数据为空,等待生产...");
              shareData.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          Integer obj = shareData.get(0);
          shareData.remove(obj);
          System.out.println(
              Thread.currentThread().getName() + " 消费数据:" + obj + ", 剩余:" + shareData.size());

          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

          shareData.notifyAll();
        }
      }
    }
  @Test
  public void testCancelled() throws InterruptedException, ExecutionException {
    Task<List<?>> t =
        Tasks.sequential(sayTask("1"), sayTask("2a", Duration.THIRTY_SECONDS, "2b"), sayTask("3"));
    ec.submit(t);
    synchronized (messages) {
      while (messages.size() <= 1) messages.wait();
    }
    Assert.assertEquals(messages, Arrays.asList("1", "2a"));
    Time.sleep(Duration.millis(50));
    t.cancel(true);
    Assert.assertTrue(t.isDone());
    // 2 should get cancelled, and invoke the cancellation semaphore
    // 3 should get cancelled and not run at all
    Assert.assertEquals(messages, Arrays.asList("1", "2a"));

    // Need to ensure that 2 has been started; race where we might cancel it before its run method
    // is even begun. Hence doing "2a; pause; 2b" where nothing is interruptable before pause.
    Assert.assertTrue(cancellations.tryAcquire(10, TimeUnit.SECONDS));

    Iterator<Task<?>> ci = ((HasTaskChildren) t).getChildren().iterator();
    Assert.assertEquals(ci.next().get(), "1");
    Task<?> task2 = ci.next();
    Assert.assertTrue(task2.isBegun());
    Assert.assertTrue(task2.isDone());
    Assert.assertTrue(task2.isCancelled());

    Task<?> task3 = ci.next();
    Assert.assertFalse(task3.isBegun());
    Assert.assertTrue(task2.isDone());
    Assert.assertTrue(task2.isCancelled());

    // but we do _not_ get a mutex from task3 as it does not run (is not interrupted)
    Assert.assertEquals(cancellations.availablePermits(), 0);
  }
  @SuppressWarnings("rawtypes")
  private EventObject waitForEvent(List events, int type) throws InterruptedException {
    // Timeout for event delivery: 3 sec
    int timeout = 30;

    EventObject eventFound = null;
    while (eventFound == null && 0 < timeout) {
      synchronized (events) {
        events.wait(100);
        for (Object aux : events) {
          if (aux instanceof BundleEvent) {
            BundleEvent event = (BundleEvent) aux;
            if (type == event.getType()) {
              eventFound = event;
              break;
            }
          } else if (aux instanceof ServiceEvent) {
            ServiceEvent event = (ServiceEvent) aux;
            if (type == event.getType()) {
              eventFound = event;
              break;
            }
          } else if (aux instanceof FrameworkEvent) {
            FrameworkEvent event = (FrameworkEvent) aux;
            if (type == event.getType()) {
              eventFound = event;
              break;
            }
          }
        }
      }
      timeout--;
    }
    return eventFound;
  }
Пример #13
0
  /**
   * Acquire a network channel from the pool. Don't lock the write stream since the connection usage
   * is exclusive.
   *
   * @param iCommand
   * @return
   * @throws IOException
   */
  protected OChannelBinaryClient beginRequest(final byte iCommand) throws IOException {
    OChannelBinaryClient network = null;

    if (debug) System.out.println("-> req: " + getSessionId());

    // FIND THE FIRST FREE CHANNEL AVAILABLE
    synchronized (networkPool) {
      final int beginCursor = networkPoolCursor;

      while (network == null) {
        if (networkPool.size() == 0) throw new ONetworkProtocolException("Connection pool closed");

        network = networkPool.get(networkPoolCursor);
        if (network.getLockWrite().tryLock()) break;

        network = null;

        networkPoolCursor++;

        if (networkPoolCursor >= networkPool.size())
          // RESTART FROM THE FIRST ONE
          networkPoolCursor = 0;

        if (networkPoolCursor == beginCursor) {
          // COMPLETE ROUND AND NOT FREE CONNECTIONS FOUND

          if (networkPool.size() < maxPool) {
            // CREATE NEW CONNECTION
            network = createNetworkConnection();
            network.getLockWrite().lock();
            networkPool.add(network);

            if (debug) System.out.println("Created new connection " + networkPool.size());
          } else {
            if (debug) System.out.println("-> req (waiting) : " + getSessionId());

            final long startToWait = System.currentTimeMillis();
            try {
              networkPool.wait(5000);
              OProfiler.getInstance().updateCounter("network.connectionPool.timeout", +1);
            } catch (InterruptedException e) {
              break;
            }

            final long elapsed =
                OProfiler.getInstance()
                    .stopChrono("network.connectionPool.waitingTime", startToWait);

            if (debug) System.out.println("Waiting for connection = elapsed: " + elapsed);
          }
        }
      }
    }

    network.writeByte(iCommand);
    network.writeInt(getSessionId());

    return network;
  }
  /**
   * Process events in the queue as they are added. The queue must be synchronized for thread safety
   * but we must be careful not to block for too long or else new events get blocked from being
   * added to the queue causing long delays. The design is to process events in batches. This allows
   * for the most efficient use of computer cycles since much of the time the queue will not be
   * blocked.
   *
   * <p>This method was modified by tap on 6/17/2004 to allow both efficient event processing and
   * thread safety. Later optimized by msekoranja.
   */
  public void run() {
    // eventBatch is local and only referenced by a single thread so we
    // don't have to synchronize it
    int eventsToProcess = 0;
    Event[] eventBatch = new Event[0];

    while (!_killed) {
      try {
        // for performance reasons we don't want to block for too long
        // synchronize _queue for thread safety
        // copy all of the new queued events to the local batch and clear _queue
        synchronized (_queue) {
          // wait for new requests
          while (!_killed && _queue.isEmpty()) _queue.wait();

          if (!_killed) {
            eventsToProcess = _queue.size();
            // create new instance of batch array only if necessary
            if (eventsToProcess > eventBatch.length) eventBatch = new Event[eventsToProcess];

            // only copy (will not recreate array)
            _queue.toArray(eventBatch);
            _queue.clear();

            // notify queue clean-up
            _queue.notifyAll();
          }
        }

        // process all events in the local batch until it is empty
        for (int i = 0; !_killed && i < eventsToProcess; i++) {
          // catch all exceptions, so that one buggy listener does not harm the others
          final Event event = eventBatch[i];
          try {
            // remove from override id
            final Object overrideId = eventBatch[i]._overrideId;
            if (overrideId != null) {
              synchronized (_overrideMap) {
                _overrideMap.remove(overrideId);
              }
            }

            event.dispatch();
          } catch (Throwable th) {
            th.printStackTrace();
          }

          decrementSyncCounter(eventBatch[i]);

          eventBatch[i] = null; // allow to be gc'ed
          Thread.yield();
        }

      } catch (Throwable th) {
        th.printStackTrace();
      }
    }
  }
Пример #15
0
 public void waitForResultCount(int count, long timeoutMillis) throws InterruptedException {
   while (collectedTuples.size() < count && timeoutMillis > 0) {
     timeoutMillis -= 20;
     synchronized (collectedTuples) {
       if (collectedTuples.size() < count) {
         collectedTuples.wait(20);
       }
     }
   }
 }
Пример #16
0
  // method used to remove an element from the list
  public String removeElement() throws InterruptedException {
    synchronized (synchedList) {

      // while the list is empty, wait
      while (synchedList.isEmpty()) {
        System.out.println("List is empty...");
        synchedList.wait();
        System.out.println("Waiting...");
      }
      String element = (String) synchedList.remove(0);

      return element;
    }
  }
Пример #17
0
  /**
   * Stops this <tt>ContactSourceService</tt> implementation and prepares it for garbage collection.
   *
   * @see AsyncContactSourceService#stop()
   */
  public void stop() {
    boolean interrupted = false;

    synchronized (queries) {
      while (!queries.isEmpty()) {
        queries.get(0).cancel();
        try {
          queries.wait();
        } catch (InterruptedException iex) {
          interrupted = true;
        }
      }
    }
    if (interrupted) Thread.currentThread().interrupt();
  }
    public void run() {
      ArrayList list2 = new ArrayList();

      while (isAlive()) {
        synchronized (list) {
          try {
            while (list.size() == 0) {
              list.wait();
            }

            if (list.size() > 0) {
              list2.addAll(list);
              list.clear();
            }
          } catch (InterruptedException ie) {
          }
        }

        if (list2.size() > 0) {
          Iterator iter = list2.iterator();

          while (iter.hasNext()) {
            String data = (String) iter.next();
            List v = decoderImpl.decodeEvents(data.trim());

            if (v != null) {
              Iterator eventIter = v.iterator();

              while (eventIter.hasNext()) {
                if (!isPaused()) {
                  doPost((LoggingEvent) eventIter.next());
                }
              }
            }
          }

          list2.clear();
        } else {
          try {
            synchronized (this) {
              wait(1000);
            }
          } catch (InterruptedException ie) {
          }
        }
      }
    }
Пример #19
0
  /**
   * {@inheritDoc}
   *
   * <p>If the Enumeration has not been closed we may have to block until we have a stream to
   * return.
   */
  public boolean hasMoreElements() {
    while (!closed) {
      synchronized (sequence) {
        if (!sequence.isEmpty()) {
          return true;
        }

        try {
          sequence.wait();
        } catch (InterruptedException woken) {
          Thread.interrupted();
        }
      }
    }

    return false;
  }
Пример #20
0
  private static void createTable(CloudataConf conf) throws IOException {
    long startTime = System.currentTimeMillis();

    int threadNum = 50;

    synchronized (threads) {
      for (int i = 0; i < threadNum; i++) {
        TableCreationThread thread =
            new TableCreationThread(
                conf, i * numOfTables / threadNum, (i + 1) * numOfTables / threadNum);
        thread.start();
        threads.add(thread);
      }
    }

    boolean end = false;
    while (!end) {
      synchronized (threads) {
        end = true;
        for (TableCreationThread eachThread : threads) {
          if (eachThread.error != null) {
            throw new IOException(eachThread.error);
          }
          if (eachThread.isAlive()) {
            end = false;
            break;
          }
        }
        if (end) {
          break;
        }

        try {
          threads.wait();
        } catch (InterruptedException e) {
        }
      }
    }
    long endTime = System.currentTimeMillis();
    System.out.println(numOfTables + " created, " + (endTime - startTime) + " ms elapsed");

    startTime = System.currentTimeMillis();
    TableSchema[] tables = CTable.listTables(conf);
    endTime = System.currentTimeMillis();
    System.out.println(tables.length + " tables listing, " + (endTime - startTime) + " ms elapsed");
  }
Пример #21
0
  /** 发送线程主控服务方法,负责调度整个处理过程 */
  public void run() {
    while (true) {
      try {
        SelectionKey key;
        synchronized (wrpool) {
          while (wrpool.isEmpty()) {
            wrpool.wait();
          }
          key = wrpool.remove(0);
        }

        // 处理写事件
        write(key);
      } catch (Exception e) {
        continue;
      }
    }
  }
Пример #22
0
 private void consume() throws InterruptedException {
   synchronized (taskQueue) {
     while (taskQueue.isEmpty()) {
       System.out.println(
           "Queue is empty "
               + Thread.currentThread().getName()
               + " is waiting , size: "
               + taskQueue.size()
               + "Time: "
               + new Date(System.currentTimeMillis()));
       taskQueue.wait();
     }
     Thread.sleep(1000);
     int i = (Integer) taskQueue.remove(0);
     System.out.println("Consumed: " + i);
     taskQueue.notifyAll();
   }
 }
Пример #23
0
  public void run() {
    ServerDataEvent dataEvent;

    while (true) {
      // Wait for data to become available
      synchronized (queue) {
        while (queue.isEmpty()) {
          try {
            queue.wait();
          } catch (InterruptedException e) {
          }
        }
        dataEvent = (ServerDataEvent) queue.remove(0);
      }

      // Return to sender
      dataEvent.server.send(dataEvent.socket, dataEvent.data);
    }
  }
Пример #24
0
  /**
   * {@inheritDoc}
   *
   * <p>If the Enumeration has not been closed we may have to block until we have a stream to
   * return.
   */
  public synchronized Object nextElement() {
    while (!closed) {
      synchronized (sequence) {
        if (sequence.isEmpty()) {
          try {
            sequence.wait();
          } catch (InterruptedException woken) {
            Thread.interrupted();
          }
          continue;
        }

        Object result = sequence.remove(0);

        return result;
      }
    }

    throw new NoSuchElementException("No more elements");
  }
Пример #25
0
    @Override
    public void run() {
      while (true) {
        synchronized (shareData) {
          while (shareData.size() == SIZE) {
            try {
              System.out.println(Thread.currentThread().getName() + " 数据是满的,等待消费...");
              shareData.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          Integer obj = random.nextInt(100);
          shareData.add(obj);
          System.out.println(
              Thread.currentThread().getName() + " 生产数据:" + obj + ", 总共:" + shareData.size());

          shareData.notifyAll();
        }
      }
    }
  protected void queueEvent(Event ev, boolean doNotBlockRequired) {
    if (_killed) return;

    // increment counter, will block if limit will be reached
    // avoid deadlock allowing recursive queue-ing
    boolean doNotBlock = doNotBlockRequired || (Thread.currentThread() == _dispatcherThread);
    incrementSyncCounter(ev, doNotBlock);

    synchronized (_queue) {
      while (!doNotBlock && _queue.size() >= _queueLimit && !_killed) {
        try {
          _queue.wait();
        } catch (InterruptedException e) {
        }
      }

      if (_killed) return;

      _queue.add(ev);
      // notify event arrival
      _queue.notifyAll();
    }
  }
 public void run() {
   while (true) {
     synchronized (pool) {
       while (pool.isEmpty()) {
         try {
           //                    	  System.out.print("is waiting pool ...\r\n");
           log.debug("--- waiting pool .................................\r\n");
           pool.wait();
         } catch (InterruptedException e) {
           e.printStackTrace();
           return;
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
       //                 System.out.print("will doing sth and pool is removing.....!\r\n");
       log.debug("will doing sth and pool is removing.....!\r\n");
       connection = (Socket) pool.remove(0);
     }
     //            System.out.print("doing sth!\r\n");
     log.debug("doing sth!\r\n");
     handleConnection();
   }
 }
  public void run() {
    // This thread loops forever, thus it should
    // be a daemon thread.
    Object previousRequest = null;
    while (true) {
      Object request = null;
      FrameworkListener[] listeners = null;
      synchronized (m_requests) {
        // Wait for a request.
        while (m_requests.isEmpty()) {
          // Terminate the thread if requested to do so (see stop()).
          if (m_thread == null) {
            return;
          }

          try {
            m_requests.wait();
          } catch (InterruptedException ex) {
            // Ignore.
          }
        }

        // Get the requested start level.
        request = m_requests.remove(0);
        listeners = m_requestListeners.remove(0);
      }

      // If the request object is an Integer, then the request
      // is to set the framework start level. If the request is
      // an Object array, then the request is to set the start
      // level for a bundle.
      // NOTE: We don't catch any exceptions here, because
      // the invoked methods shield us from exceptions by
      // catching Throwables when they invoke callbacks.
      if (request instanceof Integer) {
        // Set the new framework start level.
        try {
          m_felix.setActiveStartLevel(((Integer) request).intValue(), listeners);
        } catch (IllegalStateException ise) {
          // Thrown if global lock cannot be acquired, in which case
          // just retry (unless we already did)
          if (previousRequest == request) {
            m_felix
                .getLogger()
                .log(
                    Logger.LOG_ERROR,
                    "Unexpected problem setting active start level to " + request,
                    ise);
          } else {
            synchronized (m_requests) {
              m_requests.add(0, request);
              previousRequest = request;
            }
          }
        } catch (Exception ex) {
          m_felix
              .getLogger()
              .log(
                  Logger.LOG_ERROR,
                  "Unexpected problem setting active start level to " + request,
                  ex);
        }
      } else {
        Bundle bundle = (Bundle) ((Object[]) request)[BUNDLE_IDX];
        int startlevel = ((Integer) ((Object[]) request)[STARTLEVEL_IDX]).intValue();
        m_felix.setBundleStartLevel(bundle, startlevel);
      }

      // Notify any waiting thread that this request is done.
      synchronized (request) {
        request.notifyAll();
      }
    }
  }
Пример #29
0
 @Override
 public void run() {
   while (runing && ThreadManager.getInstance().isRunning()) {
     TaskModel r = null;
     while (taskQueue.isEmpty() && runing && ThreadManager.getInstance().isRunning()) {
       try {
         /* 任务队列为空,则等待有新任务加入从而被唤醒 */
         synchronized (taskQueue) {
           taskQueue.wait(500);
         }
       } catch (InterruptedException ie) {
         log.error(ie);
       }
     }
     synchronized (taskQueue) {
       /* 取出任务执行 */
       if (runing && ThreadManager.getInstance().isRunning()) {
         r = taskQueue.remove(0);
       }
     }
     if (r != null) {
       /* 执行任务 */
       // r.setSubmitTimeL();
       long submitTime = System.currentTimeMillis();
       try {
         r.run();
       } catch (Exception e) {
         log.error(
             "工人<“"
                 + Thread.currentThread().getName()
                 + "”> 执行任务<"
                 + r.getID()
                 + "(“"
                 + r.getName()
                 + "”)> 遇到错误: "
                 + e);
         e.printStackTrace();
       }
       long timeL1 = System.currentTimeMillis() - submitTime;
       long timeL2 = System.currentTimeMillis() - r.getSubmitTime();
       if (timeL1 <= 100L) {
         log.info(
             "工人<“"
                 + Thread.currentThread().getName()
                 + "”> 完成了任务:"
                 + r.toString()
                 + " 执行耗时:"
                 + timeL1
                 + " 提交耗时:"
                 + timeL2);
       } else if (timeL1 <= 1000L) {
         log.info(
             "工人<“"
                 + Thread.currentThread().getName()
                 + "”> 长时间执行 完成任务:"
                 + r.toString()
                 + " “考虑”任务脚本逻辑 耗时:"
                 + timeL1
                 + " 提交耗时:"
                 + timeL2);
       } else if (timeL1 <= 4000L) {
         log.info(
             "工人<“"
                 + Thread.currentThread().getName()
                 + "”> 超长时间执行完成 任务:"
                 + r.toString()
                 + " “检查”任务脚本逻辑 耗时:"
                 + timeL1
                 + " 提交耗时:"
                 + timeL2);
       } else {
         log.info(
             "工人<“"
                 + Thread.currentThread().getName()
                 + "”> 超长时间执行完成 任务:"
                 + r.toString()
                 + " “考虑是否应该删除”任务脚本 耗时:"
                 + timeL1
                 + " 提交耗时:"
                 + timeL2);
       }
       r = null;
     }
   }
   log.error("线程结束, 工人<“" + Thread.currentThread().getName() + "”>退出");
 }
Пример #30
0
  public static void main(String[] args) {
    Logger.log("JNUSTool 0.2 - by Maschell");
    Logger.log("");
    try {
      Settings.readConfig();
    } catch (IOException e) {
      System.err.println("Error while reading config! Needs to be:");
      System.err.println("DOWNLOAD URL BASE");
      System.err.println("COMMONKEY");
      System.err.println("updateinfos.csv");
      System.err.println("UPDATELIST VERSION URL");
      System.err.println("UPDATELIST URL PATTERN");
      return;
    }

    long titleID = 0;
    String key = null;
    if (args.length != 0) {
      titleID = Util.StringToLong(args[0]);
      int version = -1;
      if (args.length > 1 && args[1].length() == 32) {
        key = args[1].substring(0, 32);
      }

      if (titleID != 0) {
        String path = "";
        boolean dl_encrypted = false;
        boolean download_file = false;

        for (int i = 0; i < args.length; i++) {
          if (args[i].startsWith("v")) {
            version = Integer.parseInt((args[i].substring(1)));
          }
          if (args[i].equals("-dlEncrypted")) {
            dl_encrypted = true;
          }

          if (args[i].equals("-file")) {
            if (args.length > i) {
              i++;
              path = args[i];
            }
            download_file = true;
          }
        }
        if (dl_encrypted) {
          NUSTitle title = new NUSTitle(titleID, version, key);
          try {
            title.downloadEncryptedFiles(null);
          } catch (IOException e) {
            e.printStackTrace();
          }
          System.exit(0);
        } else if (download_file) {
          NUSTitle title = new NUSTitle(titleID, version, key);

          title.decryptFEntries(title.getFst().getFileEntriesByFilePath(path), null);

          System.exit(0);
        }

        NUSGUI m = new NUSGUI(new NUSTitle(titleID, version, key));
        m.setVisible(true);
      }
    } else {
      List<NUSTitleInformation> updatelist = UpdateListManager.getTitles();
      List<NUSTitleInformation> result = new ArrayList<>();
      if (updatelist != null) {
        UpdateChooser.createAndShowGUI(updatelist, result);
        synchronized (result) {
          try {
            result.wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }
      for (final NUSTitleInformation nus : result) {
        final long tID = nus.getTitleID();
        new Thread(
                new Runnable() {

                  @Override
                  public void run() {
                    NUSGUI m = new NUSGUI(new NUSTitle(tID, nus.getSelectedVersion(), null));
                    m.setVisible(true);
                  }
                })
            .start();
        ;
      }
    }
  }