java.util.concurrent.BlockingQueue.take()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.1k)|赞(0)|评价(0)|浏览(172)

本文整理了Java中java.util.concurrent.BlockingQueue.take()方法的一些代码示例,展示了BlockingQueue.take()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。BlockingQueue.take()方法的具体详情如下:
包路径:java.util.concurrent.BlockingQueue
类名称:BlockingQueue
方法名:take

BlockingQueue.take介绍

[英]Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
[中]检索并删除此队列的头,如有必要,等待元素可用。

代码示例

代码示例来源:origin: stackoverflow.com

class MyHouse {
  final BlockingQueue<Object> queue = new LinkedBlockingQueue<>();

  void eatFood() throws InterruptedException {
    // take next item from the queue (sleeps while waiting)
    Object food = queue.take();
    // and do something with it
    System.out.println("Eating: " + food);
  }

  void deliverPizza() throws InterruptedException {
    // in producer threads, we push items on to the queue.
    // if there is space in the queue we can return immediately;
    // the consumer thread(s) will get to it later
    queue.put("A delicious pizza");
  }
}

代码示例来源:origin: LeonardoZ/java-concurrency-patterns

public synchronized void message() throws InterruptedException {
  while (!continueToNotify)
    wait();
  String message = messages.take();
  System.out.println(message);
}

代码示例来源:origin: stanfordnlp/CoreNLP

@Override
protected Integer getProcessor() {
 try {
  return (timeout <= 0) ? idleProcessors.take() : idleProcessors.poll(timeout, TimeUnit.MILLISECONDS);
 } catch (InterruptedException e) {
  throw new RuntimeInterruptedException(e);
 }
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Wait for all threads to finish.
 * 
 * @param destroyThreadpool -- if true, then destroy the worker threads
 * so that the main thread can shutdown.
 */
public void join(boolean destroyThreadpool) {
 // Make blocking calls to the last processes that are running
 if ( ! threadPool.isShutdown()) {
  try {
   for (int i = nThreads; i > 0; --i) {
    idleProcessors.take();
   }
   if (destroyThreadpool) {
    threadPool.shutdown();
    // Sanity check. The threadpool should be done after iterating over
    // the processors.
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
   } else {
    // Repopulate the list of processors
    for (int i = 0; i < nThreads; ++i) {
     idleProcessors.put(i);
    }
   }
  } catch (InterruptedException e) {
   throw new RuntimeException(e);
  }
 }
}

代码示例来源:origin: Alluxio/alluxio

while (!Thread.currentThread().isInterrupted()) {
 try {
  Object message = mMessages.take();
  if (message == MESSAGE_DONE) {
   break;
   mStdout.println(message);
  } else if (message instanceof CopyException) {
   CopyException e = (CopyException) message;
   mStderr.println(messageAndCause(e));
  } else {
   LOG.error("Unsupported message type " + message.getClass()

代码示例来源:origin: stackoverflow.com

System.out.print(doTest(new ArrayBlockingQueue<Integer>(length), N) + "\t");
System.out.print(doTest(new SynchronousQueue<Integer>(), N));
System.out.println();
public void run() {
  for (int i = 0; i < n; i++)
    try { q.put(i); } catch (InterruptedException ex) {}
  long sum = 0;
  for (int i = 0; i < n; i++)
    try { sum += q.take(); } catch (InterruptedException ex) {}
  return sum;

代码示例来源:origin: jersey/jersey

private boolean fetchChunk(final boolean block) throws InterruptedException {
  if (eof) {
    return false;
  }
  // Read until no buffers available (poll returned null)
  // or until a non-empty buffer or EOF is reached.
  do {
    if (closed.get()) {
      current = EOF;
      break;
    }
    current = (block) ? buffers.take() : buffers.poll();
  } while (current != null && current != EOF && !current.hasRemaining());
  eof = current == EOF;
  return !eof;
}

代码示例来源:origin: apache/geode

@Override
 public void run() {
  try {
   for (;;) {
    SystemFailure.checkFailure();
    Runnable job = takeQueue.take();
    putQueue.put(job);
   }
  } catch (InterruptedException ie) {
   Thread.currentThread().interrupt();
   // this thread is being shutdown so just return;
   return;
  }
 }
};

代码示例来源:origin: stackoverflow.com

public static final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();

public static void main(String[] args) throws Exception {
  new Thread(new Runnable(){
    @Override
    public void run() {
      final int result;
      result = 2+3;
      queue.add(new Runnable(){
        @Override
        public void run() {
          System.out.println(result);
        }
      });
    }
  }).start();

  while(true) {
    queue.take().run();
  }
}

代码示例来源:origin: LeonardoZ/java-concurrency-patterns

System.out.println("=== BlockingQueue ===");
System.out.println("Queue will execute for 10s");
  while (!Thread.currentThread().isInterrupted()) {
    try {
      UUID uuid = uuidQueue.take();
      System.out.println("Consumed: " + uuid + " by " + Thread.currentThread().getName());
      UUID randomUUID = UUID.randomUUID();
      System.out.println("Produced: " + randomUUID + " by " + Thread.currentThread().getName());
      uuidQueue.put(randomUUID);

代码示例来源:origin: jersey/jersey

private boolean fetchChunk(final boolean block) throws InterruptedException {
  if (eof) {
    return false;
  }
  // Read until no buffers available (poll returned null)
  // or until a non-empty buffer or EOF is reached.
  do {
    if (closed.get()) {
      current = EOF;
      break;
    }
    current = (block) ? buffers.take() : buffers.poll();
  } while (current != null && current != EOF && !current.hasRemaining());
  eof = current == EOF;
  return !eof;
}

代码示例来源:origin: loklak/loklak_server

@Override
public MessageDigest call() {
  try {
    filechunk c;
    while(true) {
      c = this.filed.take();
      if (c == poison) break;
      this.digest.update(c.b, 0, c.n);
      this.empty.put(c);
    }
  } catch (final InterruptedException e) {
    DAO.severe(e);
  }
  return this.digest;
}

代码示例来源:origin: stackoverflow.com

.observeOn(Schedulers.from(this))
  .subscribe(message -> {
    System.out.println("Observer thread " + message);
    System.out.println("Observable thread " + Thread.currentThread().getName());
  });
tasks.take().run();

代码示例来源:origin: stackoverflow.com

public void run() {
  try {
    bq.put("A");
    bq.put("B");
    bq.put("C");
    bq.put("D");
    bq.put("E");
public void run() {
  try {
    System.out.println("1 = " + bq.take());
    System.out.println("2 = " + bq.take());
    System.out.println("3 = " + bq.take());
    System.out.println("4 = " + bq.take());
    System.out.println("5 = " + bq.take());
    System.out.println("6 = " + bq.take());
  } catch (InterruptedException ex) {
    Thread.currentThread().interrupt();

代码示例来源:origin: TooTallNate/Java-WebSocket

@Override
public void run() {
  WebSocketImpl ws = null;
  try {
    while ( true ) {
      ByteBuffer buf;
      ws = iqueue.take();
      buf = ws.inQueue.poll();
      assert ( buf != null );
      doDecode(ws, buf);
      ws = null;
    }
  } catch ( InterruptedException e ) {
    Thread.currentThread().interrupt();
  } catch ( RuntimeException e ) {
    handleFatal( ws, e );
  }
}

代码示例来源:origin: apache/geode

@Override
 public void run() {
  try {
   for (;;) {
    SystemFailure.checkFailure();
    Runnable task = takeQueue.take();
    if (forFnExec) {
     // In the function case, offer the request to the work queue.
     // If it fails, execute it anyway. This will cause the RejectedExecutionHandler to
     // spin off a thread for it.
     if (!putQueue.offer(task, OFFER_TIME, TimeUnit.MILLISECONDS)) {
      execute(task);
     }
    } else {
     // In the non-function case, put the request on the work queue.
     putQueue.put(task);
    }
   }
  } catch (InterruptedException ie) {
   Thread.currentThread().interrupt();
   // this thread is being shutdown so just return;
   return;
  }
 }
};

代码示例来源:origin: konsoletyper/teavm

public void acceptInput() throws InterruptedException {
  boolean wasAttached = debugger.isAttached();
  if (!wasAttached) {
    System.out.println("Waiting for remote process to attach...");
  }
  while (true) {
    queue.take().run();
    if (debugger.isAttached() && !wasAttached) {
      wasAttached = true;
      System.out.println("Attached");
      new Thread(() -> {
        try {
          stdinThread();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }).start();
    } else if (!debugger.isAttached() && wasAttached) {
      break;
    }
  }
  queue.offer(() -> {
    debugger.detach();
    server.stop();
  });
}

代码示例来源:origin: stackoverflow.com

private final BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
...

@Override
public onDataAvailable(int val){
  System.out.println("listener received val: " + val);
  queue.put(val);
}
...

generatorThread.addListener(listener);
generatorThread.start();
while (true) {
  // this waits for the queue to get a value
  int val = queue.take();
  System.out.println("value is: " + val);
}

代码示例来源:origin: apache/flume

private RandomAccessFile checkOut()
  throws IOException, InterruptedException {
 RandomAccessFile fileHandle = readFileHandles.poll();
 if (fileHandle != null) {
  return fileHandle;
 }
 int remaining = readFileHandles.remainingCapacity();
 if (remaining > 0) {
  LOG.info("Opening " + file + " for read, remaining number of file " +
    "handles available for reads of this file is " + remaining);
  return open();
 }
 return readFileHandles.take();
}

代码示例来源:origin: spring-projects/spring-batch

value = results.take();
  if (isContinuable(value)) {
results.put(value);
synchronized (lock) {
  while (count > results.size()) {
    lock.wait();
  value = results.take();
  count--;

相关文章