当前位置: 首页>>代码示例>>Java>>正文


Java BlockingQueue类代码示例

本文整理汇总了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;
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:20,代码来源:MoreExecutors.java

示例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;
        }
      });
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:18,代码来源:ThreadPoolEventTarget.java

示例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);
			}
		}
	}
}
 
开发者ID:equella,项目名称:Equella,代码行数:24,代码来源:LocalTaskServiceImpl.java

示例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));
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:ArrayBlockingQueueTest.java

示例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);
}
 
开发者ID:isuperqiang,项目名称:AndEasyLog,代码行数:17,代码来源:ThreadHelper.java

示例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());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:DrainToFails.java

示例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);
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:18,代码来源:ArbitraryInstancesTest.java

示例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();
    }
  }
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:27,代码来源:Uninterruptibles.java

示例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);
}
 
开发者ID:dewey-its,项目名称:apollo-custom,代码行数:23,代码来源:InstanceConfigAuditUtilTest.java

示例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
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:8,代码来源:SmokeTest.java

示例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 ;
}
 
开发者ID:m18507308080,项目名称:bohemia,代码行数:21,代码来源:Cz88Job.java

示例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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:CancelledProducerConsumerLoops.java

示例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);
}
 
开发者ID:salesforce,项目名称:storm-dynamic-spout,代码行数:25,代码来源:RoundRobinBuffer.java

示例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);
    }

}
 
开发者ID:yu199195,项目名称:happylifeplat-transaction,代码行数:16,代码来源:TransactionThreadPool.java

示例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();
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:8,代码来源:FlexibleThreadPoolWrapper.java


注:本文中的java.util.concurrent.BlockingQueue类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。