public void run() {
   producer.getReady();
   MyBlockingQueue<Integer> buffer = producer.getBuffer();
   Integer item = buffer.take();
   while (item != null) {
     System.out.println(this + " fetches " + item + ".");
     Thread.yield();
     item = buffer.take();
   }
 }
  public static void main(String[] args) {
    final AttemptLocking al = new AttemptLocking();
    al.untimed(); // True -- lock is available
    al.timed(); // True -- lock is available
    // Now create a separate task to grab the lock:
    new Thread() {
      {
        setDaemon(true);
      }

      public void run() {
        al.lock.lock();
        System.out.println("acquired");
      }
    }.start();
    Thread.yield(); // Give the 2nd task a chance
    al.untimed(); // False -- lock grabbed by task
    al.timed(); // False -- lock grabbed by task
  }
Пример #3
0
 /**
  * Look for data from all the inputs
  *
  * @return true if data was consumed
  */
 private boolean poll(Signal signal, Signal parent) {
   AtomicReferenceArray<T> o = outputs;
   for (int i = 0; i < o.length(); i++) {
     T input = o.getAndSet(i, null);
     if (input == null) continue;
     long seq = ++sequence;
     if (parent != null) parent.signal();
     S product = producer.execute(input, reuseReceptors.get(i), signal);
     signal.signal();
     if (!consume(product, seq, 0)) {
       Thread.yield();
       if (!consume(product, seq, 0))
         logger.info(
             "failed to consume product (" + product + ") from producer (" + producer + ")");
     }
     producer.complete(product);
     return product != null;
   }
   return false;
 }
Пример #4
0
 @Override
 public void run() {
   try {
     while (started) {
       int result = execute();
       if (result < 0) break;
       if (result > 0) {
         if (sleep > 0) {
           Thread.sleep(sleep);
           sleptTime += sleep;
         } else if (sleep < 0) Thread.yield();
       } else if (adding) {
         Thread.sleep(1);
       } else {
         if (sleep > 0) {
           incrementTime++;
           if (incrementTime % 1_000_000 == 0) {
             toSleepTime += sleep;
             if (sleptTime < toSleepTime) {
               sleptTime += sleep;
               Thread.sleep(sleep);
             }
           }
         }
       }
     }
   } catch (InterruptedException e) {
     if (started) {
       if (listener == null) logger.warn("polling", e);
       else listener.exceptionThrown(e);
     }
   } catch (Exception e) {
     if (listener == null) logger.error("polling", e);
     else listener.exceptionThrown(e);
   }
 }