本文整理汇总了Java中java.util.concurrent.BlockingQueue类的典型用法代码示例。如果您正苦于以下问题:Java BlockingQueue类的具体用法?Java BlockingQueue怎么用?Java BlockingQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BlockingQueue类属于java.util.concurrent包,在下文中一共展示了BlockingQueue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: submitAndAddQueueListener
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
/**
* Submits the task and adds a listener that adds the future to {@code queue} when it completes.
*/
@GwtIncompatible // TODO
private static <T> ListenableFuture<T> submitAndAddQueueListener(
ListeningExecutorService executorService,
Callable<T> task,
final BlockingQueue<Future<T>> queue) {
final ListenableFuture<T> future = executorService.submit(task);
future.addListener(
new Runnable() {
@Override
public void run() {
queue.add(future);
}
},
directExecutor());
return future;
}
示例2: ThreadPoolEventTarget
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
public ThreadPoolEventTarget(
final ThreadFactory wrappedFactory, final ThreadInitializer threadInitializer) {
int poolSize = 1;
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
executor = new ThreadPoolExecutor(poolSize, poolSize, 3, TimeUnit.SECONDS, queue,
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = wrappedFactory.newThread(r);
threadInitializer.setName(thread, "FirebaseDatabaseEventTarget");
threadInitializer.setDaemon(thread, true);
threadInitializer.setUncaughtExceptionHandler(thread, ThreadPoolEventTarget.this);
return thread;
}
});
}
示例3: processMessage
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
private void processMessage(String taskId, SimpleMessage message, boolean request)
{
synchronized( stateMutex )
{
if( request )
{
Task task = runningTasks.get(taskId);
if( task != null )
{
task.postMessage(message);
}
}
else
{
BlockingQueue<SimpleMessage> waitingQueue = messageResponses.getIfPresent(message.getMessageId());
if( waitingQueue != null )
{
messageResponses.invalidate(message.getMessageId());
waitingQueue.add(message);
}
}
}
}
示例4: testRemainingCapacity
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
/**
* remainingCapacity decreases on add, increases on remove
*/
public void testRemainingCapacity() {
int size = ThreadLocalRandom.current().nextInt(1, SIZE);
BlockingQueue q = populatedQueue(size, size, 2 * size, false);
int spare = q.remainingCapacity();
int capacity = spare + size;
for (int i = 0; i < size; i++) {
assertEquals(spare + i, q.remainingCapacity());
assertEquals(capacity, q.size() + q.remainingCapacity());
assertEquals(i, q.remove());
}
for (int i = 0; i < size; i++) {
assertEquals(capacity - i, q.remainingCapacity());
assertEquals(capacity, q.size() + q.remainingCapacity());
assertTrue(q.add(i));
}
}
示例5: ThreadHelper
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
private ThreadHelper() {
mMainHandler = new Handler(Looper.getMainLooper());
ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "ThreadHelper #".concat(String.valueOf(mCount.getAndIncrement())));
}
};
int cpuCount = Runtime.getRuntime().availableProcessors();
int corePoolSize = cpuCount + 1;
int maxPoolSize = cpuCount * 2 + 1;
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(128);
mExecutorService = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 10, TimeUnit.SECONDS, queue, threadFactory);
}
示例6: testDelayQueue
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
void testDelayQueue(final BlockingQueue q) throws Throwable {
System.err.println(q.getClass().getSimpleName());
for (int i = 0; i < CAPACITY; i++)
q.add(new PDelay(i));
ArrayBlockingQueue q2 = new ArrayBlockingQueue(SMALL);
try {
q.drainTo(q2, SMALL + 3);
fail("should throw");
} catch (IllegalStateException success) {
equal(SMALL, q2.size());
equal(new PDelay(0), q2.poll());
equal(new PDelay(1), q2.poll());
check(q2.isEmpty());
for (int i = SMALL; i < CAPACITY; i++)
equal(new PDelay(i), q.poll());
equal(0, q.size());
}
}
示例7: testGet_concurrent
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
public void testGet_concurrent() {
assertTrue(ArbitraryInstances.get(BlockingDeque.class).isEmpty());
assertTrue(ArbitraryInstances.get(BlockingQueue.class).isEmpty());
assertTrue(ArbitraryInstances.get(DelayQueue.class).isEmpty());
assertTrue(ArbitraryInstances.get(SynchronousQueue.class).isEmpty());
assertTrue(ArbitraryInstances.get(PriorityBlockingQueue.class).isEmpty());
assertTrue(ArbitraryInstances.get(ConcurrentMap.class).isEmpty());
assertTrue(ArbitraryInstances.get(ConcurrentNavigableMap.class).isEmpty());
ArbitraryInstances.get(Executor.class).execute(ArbitraryInstances.get(Runnable.class));
assertNotNull(ArbitraryInstances.get(ThreadFactory.class));
assertFreshInstanceReturned(
BlockingQueue.class, BlockingDeque.class, PriorityBlockingQueue.class,
DelayQueue.class, SynchronousQueue.class,
ConcurrentMap.class, ConcurrentNavigableMap.class,
AtomicReference.class, AtomicBoolean.class,
AtomicInteger.class, AtomicLong.class, AtomicDouble.class);
}
示例8: putUninterruptibly
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
/**
* Invokes {@code queue.}{@link BlockingQueue#put(Object) put(element)} uninterruptibly.
*
* @throws ClassCastException if the class of the specified element prevents it from being added
* to the given queue
* @throws IllegalArgumentException if some property of the specified element prevents it from
* being added to the given queue
*/
@GwtIncompatible // concurrency
public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) {
boolean interrupted = false;
try {
while (true) {
try {
queue.put(element);
return;
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
示例9: setUp
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
instanceConfigAuditUtil = new InstanceConfigAuditUtil();
ReflectionTestUtils.setField(instanceConfigAuditUtil, "instanceService", instanceService);
audits = (BlockingQueue<InstanceConfigAuditUtil.InstanceConfigAuditModel>)
ReflectionTestUtils.getField(instanceConfigAuditUtil, "audits");
someAppId = "someAppId";
someClusterName = "someClusterName";
someDataCenter = "someDataCenter";
someIp = "someIp";
someConfigAppId = "someConfigAppId";
someConfigClusterName = "someConfigClusterName";
someConfigNamespace = "someConfigNamespace";
someReleaseKey = "someReleaseKey";
someAuditModel = new InstanceConfigAuditUtil.InstanceConfigAuditModel(someAppId,
someClusterName, someDataCenter, someIp, someConfigAppId, someConfigClusterName,
someConfigNamespace, someReleaseKey);
}
示例10: putQ
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
static void putQ(BlockingQueue<String> q, String o) {
try {
q.put(o);
} catch (InterruptedException e) {
// can't happen
}
}
示例11: execute
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
@Override
public JobResult execute(BlockingQueue<String> jobPathArray) {
String currentThreadName = Thread.currentThread().getName();
logger.info(" [cz88.net] 线程[" + currentThreadName + "] 爬虫JOB 开始工作 ");
JobResult jobResult = new JobResult();
String url = null ;
try {
while ((url = jobPathArray.poll()) != null) {
BaseUtil.getInstance().getRedisClient().lpush(Constant.WEBSITE_CODE_QUEUE_CZ88, url) ;
}
} catch (Exception e) {
logger.info("Redis 连接异常 , 网络是否畅通 , 服务是否启动") ;
}
if (null == url) {
logger.info(" [cz88.net] 线程[" + currentThreadName + "] 发现队列为空 停止工作 ");
CrawlersTaskPool.sharedInstance().getExecutor().shutdown();
}
logger.info(" [cz88.net] 线程[" + currentThreadName + "] 爬虫JOB 结束工作 ");
return jobResult ;
}
示例12: main
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
final int maxPairs = (args.length > 0) ? Integer.parseInt(args[0]) : 5;
pool = Executors.newCachedThreadPool();
for (int i = 1; i <= maxPairs; i += (i+1) >>> 1) {
final List<BlockingQueue<Integer>> queues = new ArrayList<>();
queues.add(new ArrayBlockingQueue<Integer>(100));
queues.add(new LinkedBlockingQueue<Integer>(100));
queues.add(new LinkedBlockingDeque<Integer>(100));
queues.add(new SynchronousQueue<Integer>());
// unbounded queue implementations are prone to OOME:
// PriorityBlockingQueue, LinkedTransferQueue
for (BlockingQueue<Integer> queue : queues)
new CancelledProducerConsumerLoops(i, queue).run();
}
pool.shutdown();
if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
throw new AssertionError("timed out");
pool = null;
}
示例13: put
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
/**
* Put a new message onto the queue. This method is blocking if the queue buffer is full.
* @param message - Message to be added to the queue.
* @throws InterruptedException - thrown if a thread is interrupted while blocked adding to the queue.
*/
@Override
public void put(final Message message) throws InterruptedException {
// Grab the source virtual spoutId
final VirtualSpoutIdentifier virtualSpoutId = message.getMessageId().getSrcVirtualSpoutId();
// Add to correct buffer
BlockingQueue<Message> virtualSpoutQueue = messageBuffer.get(virtualSpoutId);
// If our queue doesn't exist
if (virtualSpoutQueue == null) {
// Attempt to put it
messageBuffer.putIfAbsent(virtualSpoutId, createNewEmptyQueue());
// Grab a reference.
virtualSpoutQueue = messageBuffer.get(virtualSpoutId);
}
// Put it.
virtualSpoutQueue.put(message);
}
示例14: createBlockingQueue
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
private BlockingQueue<Runnable> createBlockingQueue() {
BlockingQueueTypeEnum queueType = BlockingQueueTypeEnum.fromString(txConfig.getBlockingQueueType());
switch (queueType) {
case LINKED_BLOCKING_QUEUE:
return new LinkedBlockingQueue<>(1024);
case ARRAY_BLOCKING_QUEUE:
return new ArrayBlockingQueue<>(MAX_ARRAY_QUEUE);
case SYNCHRONOUS_QUEUE:
return new SynchronousQueue<>();
default:
return new LinkedBlockingQueue<>(1024);
}
}
示例15: FlexibleThreadPoolWrapper
import java.util.concurrent.BlockingQueue; //导入依赖的package包/类
private FlexibleThreadPoolWrapper(int minThreadCount, int maxThreadCount, long keepAlive, TimeUnit timeUnit,
ThreadFactory threadFactory, BlockingQueue<Runnable> queue) {
executor = new ThreadPoolExecutor(minThreadCount, maxThreadCount, keepAlive, timeUnit,
queue, threadFactory, new FlexibleRejectionHandler());
executor.prestartAllCoreThreads();
}