本文整理汇总了Java中java.util.concurrent.BlockingQueue.take方法的典型用法代码示例。如果您正苦于以下问题:Java BlockingQueue.take方法的具体用法?Java BlockingQueue.take怎么用?Java BlockingQueue.take使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.BlockingQueue
的用法示例。
在下文中一共展示了BlockingQueue.take方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: output
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* Output the items in the stream with a function.
* This method will block until the result returns.
* Eg. `output(StatisticOperators.count())` will output the number of items.
*
* @param itemsCollector the function used to output current stream
* @param <Tout> the type of the result
* @return the result
* @throws PSException if failed to the result.
*/
@PSAction(blocking = true)
public <Tout> Tout output(Function<List<Item>, Tout> itemsCollector) throws PSException {
final BlockingQueue<Object> resultQueue = new LinkedBlockingQueue<>();
Callback<Tout> resultHandler = new Callback<Tout>() {
@Override
protected void onInput(Tout input) {
resultQueue.add(input);
}
@Override
protected void onFail(PSException exception) {
resultQueue.add(exception);
}
};
this.output(itemsCollector, resultHandler);
try {
Object resultOrException = resultQueue.take();
if (resultOrException instanceof PSException) {
throw (PSException) resultOrException;
}
return (Tout) resultOrException;
} catch (InterruptedException e) {
throw PSException.INTERRUPTED(e.getMessage());
}
}
示例2: takeUninterruptibly
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly.
*/
@GwtIncompatible // concurrency
public static <E> E takeUninterruptibly(BlockingQueue<E> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
示例3: call
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
public String call(String message) throws IOException, InterruptedException {
String corrId = UUID.randomUUID().toString();
AMQP.BasicProperties props = new AMQP.BasicProperties
.Builder()
.correlationId(corrId)
.replyTo(replyQueueName)
.build();
channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
if (properties.getCorrelationId().equals(corrId)) {
response.offer(new String(body, "UTF-8"));
}
}
});
return response.take();
}
示例4: getResult
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
/**
* 获取结果
* @param blockingQueue
* @param timeout
* @param unit
* @return
* @throws InterruptedIOException
*/
public static Object getResult(BlockingQueue<Object> blockingQueue,long timeout, TimeUnit unit) throws InterruptedIOException {
Object result;
try {
result = blockingQueue.poll(timeout, unit);
if (result == null) {
if (!blockingQueue.offer("")) {
result = blockingQueue.take();
}
}
} catch (InterruptedException e) {
throw ExceptionUtil.initCause(new InterruptedIOException(e.getMessage()), e);
}
return result;
}
示例5: consume
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
private DataFrame consume(BlockingQueue<DataFrame> bq) throws InterruptedException {
DataFrame dfRet = null;
//TODO PARAMETRIZAR
int timeOverlap = WINDOW_SZ/2;
dfRet = bq.take();
//ENVIAMOS AL PROCESO DE RECOGIDA LA COLA EL ULTIMO MEDIO SEGUNDO DE RECOGIDA
int row = dfRet.length() - 1;
int rowFinal = row;
long timestampFinal = (long) dfRet.get(rowFinal, 0);
long timestampActual = (long) dfRet.get(row, 0);
//TODO PARAMETRIZAR NUMEROS
while((timestampFinal - timestampActual) <= (timeOverlap - 15)){
row--;
timestampActual = (long) dfRet.get(row, 0);
}
//TODO HACER SLICE DEL DF [ROW, ROWFINAL] Y METERLO A LA COLA PARA QUE LO COJA EL SERVICIO DE RECOGIDA DE DATOS
DataFrame df = dfRet.slice(row, rowFinal + 1);
this.queueProcRecog.put(df);
return dfRet;
}
示例6: testNegativeMaxElements
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
private void testNegativeMaxElements(BlockingQueue<Object> q) throws InterruptedException {
@SuppressWarnings("unused") // go/futurereturn-lsc
Future<?> possiblyIgnoredError = threadPool.submit(new Producer(q, 1));
List<Object> buf = newArrayList();
int elements = Queues.drain(q, buf, -1, MAX_VALUE, NANOSECONDS);
assertEquals(elements, 0);
assertThat(buf).isEmpty();
// Free the producer thread, and give subsequent tests a clean slate.
q.take();
}
示例7: takeQ
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
static String takeQ(BlockingQueue<String> q) {
String r = null;
try {
r = q.take();
} catch (InterruptedException e) {}
return r;
}
示例8: testNegativeMaxElements
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
private void testNegativeMaxElements(BlockingQueue<Object> q) throws InterruptedException {
threadPool.submit(new Producer(q, 1));
List<Object> buf = newArrayList();
int elements = Queues.drain(q, buf, -1, MAX_VALUE, NANOSECONDS);
assertEquals(elements, 0);
assertThat(buf).isEmpty();
// Free the producer thread, and give subsequent tests a clean slate.
q.take();
}
示例9: getMessages
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
protected MatrixCursor getMessages(String[] projection) throws InterruptedException {
BlockingQueue<List<MessageInfoHolder>> queue = new SynchronousQueue<List<MessageInfoHolder>>();
// new code for integrated inbox, only execute this once as it will be processed afterwards via the listener
SearchAccount integratedInboxAccount = SearchAccount.createUnifiedInboxAccount(getContext());
MessagingController msgController = MessagingController.getInstance(getContext());
msgController.searchLocalMessages(integratedInboxAccount.getRelatedSearch(),
new MessageInfoHolderRetrieverListener(queue));
List<MessageInfoHolder> holders = queue.take();
// TODO add sort order parameter
Collections.sort(holders, new ReverseDateComparator());
String[] projectionToUse;
if (projection == null) {
projectionToUse = DEFAULT_MESSAGE_PROJECTION;
} else {
projectionToUse = projection;
}
LinkedHashMap<String, FieldExtractor<MessageInfoHolder, ?>> extractors =
resolveMessageExtractors(projectionToUse, holders.size());
int fieldCount = extractors.size();
String[] actualProjection = extractors.keySet().toArray(new String[fieldCount]);
MatrixCursor cursor = new MatrixCursor(actualProjection);
for (MessageInfoHolder holder : holders) {
Object[] o = new Object[fieldCount];
int i = 0;
for (FieldExtractor<MessageInfoHolder, ?> extractor : extractors.values()) {
o[i] = extractor.getField(holder);
i += 1;
}
cursor.addRow(o);
}
return cursor;
}
示例10: stream
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
public Stream<TweetHandler> stream() {
String myKey = "sl2WbCf4UnIr08xvHVitHJ99r";
String mySecret = "PE6yauvXjKLuvoQNXZAJo5C8N5U5piSFb3udwkoI76paK6KyqI";
String myToken = "1098376471-p6iWfxCLtyMvMutTb010w1D1xZ3UyJhcC2kkBjN";
String myAccess = "2o1uGcp4b2bFynOfu2cA1uz63n5aruV0RwNsUjRpjDBZS";
out.println("Creating Twitter Stream");
BlockingQueue<String> statusQueue = new LinkedBlockingQueue<>(1000);
StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
endpoint.trackTerms(Lists.newArrayList("twitterapi", this.topic));
endpoint.stallWarnings(false);
Authentication twitterAuth = new OAuth1(myKey, mySecret, myToken, myAccess);
BasicClient twitterClient = new ClientBuilder()
.name("Twitter client")
.hosts(Constants.STREAM_HOST)
.endpoint(endpoint)
.authentication(twitterAuth)
.processor(new StringDelimitedProcessor(statusQueue))
.build();
twitterClient.connect();
List<TweetHandler> list = new ArrayList();
List<String> twitterList = new ArrayList();
statusQueue.drainTo(twitterList);
for(int i=0; i<numberOfTweets; i++) {
String message;
try {
message = statusQueue.take();
list.add(new TweetHandler(message));
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
// for (int msgRead = 0; msgRead < this.numberOfTweets; msgRead++) {
// try {
// if (twitterClient.isDone()) {
// // out.println(twitterClient.getExitEvent().getMessage());
// break;
// }
//
// String msg = statusQueue.poll(10, TimeUnit.SECONDS);
// if (msg == null) {
// out.println("Waited 10 seconds - no message received");
// } else {
// list.add(new TweetHandler(msg));
// out.println("Added message: " + msg.length());
// }
// } catch (InterruptedException ex) {
// ex.printStackTrace();
// }
// }
twitterClient.stop();
out.printf("%d messages processed!\n", twitterClient.getStatsTracker().getNumMessages());
return list.stream();
}
开发者ID:PacktPublishing,项目名称:Machine-Learning-End-to-Endguide-for-Java-developers,代码行数:61,代码来源:TwitterStream.java
示例11: ownThreadJob
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
@Override
protected void ownThreadJob(Object... objects) {
try {
ArrayMinHeap<HeapItem> heap = new ArrayMinHeap<>(new Comparator<HeapItem>() {
@Override
public int compare(HeapItem o1, HeapItem o2) {
RowDataPacket row1 = o1.getRowPacket();
RowDataPacket row2 = o2.getRowPacket();
if (row1 == null || row2 == null) {
if (row1 == row2)
return 0;
if (row1 == null)
return -1;
return 1;
}
return rowComparator.compare(row1, row2);
}
});
// init heap
for (Map.Entry<MySQLConnection, BlockingQueue<HeapItem>> entry : queues.entrySet()) {
HeapItem firstItem = entry.getValue().take();
heap.add(firstItem);
}
while (!heap.isEmpty()) {
if (terminate.get())
return;
HeapItem top = heap.peak();
if (top.isNullItem()) {
heap.poll();
} else {
BlockingQueue<HeapItem> topItemQueue = queues.get(top.getIndex());
HeapItem item = topItemQueue.take();
heap.replaceTop(item);
if (nextHandler.rowResponse(top.getRowData(), top.getRowPacket(), this.isLeft, top.getIndex())) {
noNeedRows = true;
while (!heap.isEmpty()) {
HeapItem itemToDiscard = heap.poll();
if (!itemToDiscard.isNullItem()) {
BlockingQueue<HeapItem> discardQueue = queues.get(itemToDiscard.getIndex());
while (true) {
if (discardQueue.take().isNullItem() || terminate.get()) {
break;
}
}
}
}
}
}
}
if (LOGGER.isInfoEnabled()) {
String executeQueries = getRoutesSql(route);
LOGGER.info(executeQueries + " heap send eof: ");
}
nextHandler.rowEofResponse(null, this.isLeft, queues.keySet().iterator().next());
} catch (Exception e) {
String msg = "Merge thread error, " + e.getLocalizedMessage();
LOGGER.info(msg, e);
session.onQueryError(msg.getBytes());
}
}
示例12: consume
import java.util.concurrent.BlockingQueue; //导入方法依赖的package包/类
private DataFrame consume(BlockingQueue<DataFrame> bq) throws InterruptedException {
DataFrame dfRet = null;
dfRet = bq.take();
return dfRet;
}