本文整理汇总了Java中java.util.concurrent.ArrayBlockingQueue类的典型用法代码示例。如果您正苦于以下问题:Java ArrayBlockingQueue类的具体用法?Java ArrayBlockingQueue怎么用?Java ArrayBlockingQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ArrayBlockingQueue类属于java.util.concurrent包,在下文中一共展示了ArrayBlockingQueue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setUp
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
@BeforeExperiment void setUp() throws Exception {
executorService = new ThreadPoolExecutor(NUM_THREADS,
NUM_THREADS,
Long.MAX_VALUE,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(1000));
executorService.prestartAllCoreThreads();
final AtomicInteger integer = new AtomicInteger();
// Execute a bunch of tasks to ensure that our threads are allocated and hot
for (int i = 0; i < NUM_THREADS * 10; i++) {
@SuppressWarnings("unused") // go/futurereturn-lsc
Future<?> possiblyIgnoredError =
executorService.submit(
new Runnable() {
@Override
public void run() {
integer.getAndIncrement();
}
});
}
}
示例2: testInterruptedSubmit
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* submit(callable).get() throws InterruptedException if interrupted
*/
public void testInterruptedSubmit() throws InterruptedException {
final CountDownLatch submitted = new CountDownLatch(1);
final CountDownLatch quittingTime = new CountDownLatch(1);
final Callable<Void> awaiter = new CheckedCallable<Void>() {
public Void realCall() throws InterruptedException {
assertTrue(quittingTime.await(2*LONG_DELAY_MS, MILLISECONDS));
return null;
}};
final ExecutorService p
= new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p, quittingTime)) {
Thread t = newStartedThread(new CheckedInterruptedRunnable() {
public void realRun() throws Exception {
Future<Void> future = p.submit(awaiter);
submitted.countDown();
future.get();
}});
await(submitted);
t.interrupt();
awaitTermination(t);
}
}
示例3: testOffer
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* This test tests the CheckedQueue.offer method.
*/
@Test
public void testOffer() {
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue(1);
Queue q = Collections.checkedQueue(abq, String.class);
try {
q.offer(null);
fail("should throw NullPointerException.");
} catch (NullPointerException npe) {
// Do nothing
}
try {
q.offer(0);
fail("should throw ClassCastException.");
} catch (ClassCastException cce) {
// Do nothing
}
assertTrue(q.offer("0"), "queue should have room");
// no room at the inn!
assertFalse(q.offer("1"), "queue should be full");
}
示例4: main
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
final int maxConsumers = (args.length > 0)
? Integer.parseInt(args[0])
: 5;
pool = Executors.newCachedThreadPool();
for (int i = 1; i <= maxConsumers; i += (i+1) >>> 1) {
// Adjust iterations to limit typical single runs to <= 10 ms;
// Notably, fair queues get fewer iters.
// Unbounded queues can legitimately OOME if iterations
// high enough, but we have a sufficiently low limit here.
run(new ArrayBlockingQueue<Integer>(100), i, 1000);
run(new LinkedBlockingQueue<Integer>(100), i, 1000);
run(new LinkedBlockingDeque<Integer>(100), i, 1000);
run(new LinkedTransferQueue<Integer>(), i, 700);
run(new PriorityBlockingQueue<Integer>(), i, 1000);
run(new SynchronousQueue<Integer>(), i, 300);
run(new SynchronousQueue<Integer>(true), i, 200);
run(new ArrayBlockingQueue<Integer>(100, true), i, 100);
}
pool.shutdown();
if (! pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
throw new Error();
pool = null;
}
示例5: testPollInExecutor
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* timed poll retrieves elements across Executor threads
*/
public void testPollInExecutor() {
final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
final CheckedBarrier threadsStarted = new CheckedBarrier(2);
final ExecutorService executor = Executors.newFixedThreadPool(2);
try (PoolCleaner cleaner = cleaner(executor)) {
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
assertNull(q.poll());
threadsStarted.await();
assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
checkEmpty(q);
}});
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
threadsStarted.await();
q.put(one);
}});
}
}
示例6: Demodulator
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* Constructor. Creates a new demodulator block reading its samples from the given input queue and
* returning the buffers to the given output queue. Expects input samples to be at baseband (mixing
* is done by the scheduler)
*
* @param inputQueue Queue that delivers received baseband signals
* @param outputQueue Queue to return used buffers from the inputQueue
* @param packetSize Size of the packets in the input queue
*/
public Demodulator (ArrayBlockingQueue<SamplePacket> inputQueue, ArrayBlockingQueue<SamplePacket> outputQueue, int packetSize) {
// Create internal sample buffers:
// Note that we create the buffers for the case that there is no downsampling necessary
// All other cases with input decimation > 1 are also possible because they only need
// smaller buffers.
this.quadratureSamples = new SamplePacket(packetSize);
// Create Audio Sink
this.audioSink = new AudioSink(packetSize, AUDIO_RATE);
// Create Decimator block
// Note that the decimator directly reads from the inputQueue and also returns processed packets to the
// output queue.
this.decimator = new Decimator(QUADRATURE_RATE[demodulationMode], packetSize, inputQueue, outputQueue);
}
示例7: addToSendQueue
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* Inserts an element in the specified queue. If the Queue is full, this
* method removes an element from the head of the Queue and then inserts
* the element at the tail. It can happen that the an element is removed
* by another thread in {@link SendWorker#processMessage() processMessage}
* method before this method attempts to remove an element from the queue.
* This will cause {@link ArrayBlockingQueue#remove() remove} to throw an
* exception, which is safe to ignore.
*
* Unlike {@link #addToRecvQueue(Message) addToRecvQueue} this method does
* not need to be synchronized since there is only one thread that inserts
* an element in the queue and another thread that reads from the queue.
*
* @param queue
* Reference to the Queue
* @param buffer
* Reference to the buffer to be inserted in the queue
*/
private void addToSendQueue(ArrayBlockingQueue<ByteBuffer> queue,
ByteBuffer buffer) {
if (queue.remainingCapacity() == 0) {
try {
queue.remove();
} catch (NoSuchElementException ne) {
// element could be removed by poll()
LOG.debug("Trying to remove from an empty " +
"Queue. Ignoring exception " + ne);
}
}
try {
queue.add(buffer);
} catch (IllegalStateException ie) {
// This should never happen
LOG.error("Unable to insert an element in the queue " + ie);
}
}
示例8: Decimator
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* Constructor. Will create a new Decimator block.
*
* @param outputSampleRate // sample rate to which the incoming samples should be decimated
* @param packetSize // packet size of the incoming sample packets
* @param inputQueue // queue that delivers incoming sample packets
* @param inputReturnQueue // queue to return used input sample packets
*/
public Decimator (int outputSampleRate, int packetSize, ArrayBlockingQueue<SamplePacket> inputQueue,
ArrayBlockingQueue<SamplePacket> inputReturnQueue) {
this.outputSampleRate = outputSampleRate;
this.packetSize = packetSize;
this.inputQueue = inputQueue;
this.inputReturnQueue = inputReturnQueue;
// Create output queues:
this.outputQueue = new ArrayBlockingQueue<SamplePacket>(OUTPUT_QUEUE_SIZE);
this.outputReturnQueue = new ArrayBlockingQueue<SamplePacket>(OUTPUT_QUEUE_SIZE);
for (int i = 0; i < OUTPUT_QUEUE_SIZE; i++)
outputReturnQueue.offer(new SamplePacket(packetSize));
// Create half band filters for downsampling:
this.inputFilter1 = new HalfBandLowPassFilter(8);
this.inputFilter2 = new HalfBandLowPassFilter(8);
this.inputFilter3 = new HalfBandLowPassFilter(8);
// Create local buffers:
this.tmpDownsampledSamples = new SamplePacket(packetSize);
}
示例9: getExecutorService
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* @return that may be used to perform processesing asynchronously.
*/
protected static ExecutorService getExecutorService() {
if (JDBCSQLXML.executorService == null) {
int corePoolSize = 1;
int maximumPoolSize = 10;
long keepAliveTime = 1;
TimeUnit unit = TimeUnit.SECONDS;
JDBCSQLXML.workQueue = new ArrayBlockingQueue<Runnable>(10);
JDBCSQLXML.executorService = new ThreadPoolExecutor(corePoolSize,
maximumPoolSize, keepAliveTime, unit, workQueue);
}
return executorService;
}
示例10: testTimedInvokeAny5
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* timed invokeAny(c) returns result of some task
*/
public void testTimedInvokeAny5() throws Exception {
final ExecutorService e =
new CustomTPE(2, 2,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(e)) {
long startTime = System.nanoTime();
List<Callable<String>> l = new ArrayList<>();
l.add(new StringTask());
l.add(new StringTask());
String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
assertSame(TEST_STRING, result);
assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
}
}
示例11: testRejectedRecycledTask
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* execute allows the same task to be submitted multiple times, even
* if rejected
*/
public void testRejectedRecycledTask() throws InterruptedException {
final int nTasks = 1000;
final CountDownLatch done = new CountDownLatch(nTasks);
final Runnable recycledTask = new Runnable() {
public void run() {
done.countDown();
}};
final ThreadPoolExecutor p =
new ThreadPoolExecutor(1, 30,
60, SECONDS,
new ArrayBlockingQueue(30));
try (PoolCleaner cleaner = cleaner(p)) {
for (int i = 0; i < nTasks; ++i) {
for (;;) {
try {
p.execute(recycledTask);
break;
}
catch (RejectedExecutionException ignore) {}
}
}
// enough time to run all tasks
await(done, nTasks * SHORT_DELAY_MS);
}
}
示例12: start
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
@Override
public void start() throws Exception {
LOGGER.info("Start called");
Assert.isTrue(stopped);
stopped = false;
queue = new ArrayBlockingQueue<CommandWrapper>(100000);
// Thread de consommation
consumationThread = new Thread(this);
consumationThread.setName("TiPi-Consumer");
consumationThread.setPriority(Thread.NORM_PRIORITY + 1);
LOGGER.info("Démarrage du Thread de CommandConsumer ...");
consumationThread.start();
if (resumeTipiAtBoot) {
// Reveille les taches tout de suite
LOGGER.info("Cold restart TiPi ...");
addCommand(new ColdRestartCommand());
} else {
LOGGER.info("Pas de Cold restart de TiPi");
}
}
示例13: LeaderState
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
LeaderState(RaftServerImpl server, RaftProperties properties) {
this.server = server;
stagingCatchupGap = RaftServerConfigKeys.stagingCatchupGap(properties);
syncInterval = RaftServerConfigKeys.Rpc.sleepTime(properties);
final ServerState state = server.getState();
this.raftLog = state.getLog();
this.currentTerm = state.getCurrentTerm();
eventQ = new ArrayBlockingQueue<>(4096);
processor = new EventProcessor();
pendingRequests = new PendingRequests(server);
final RaftConfiguration conf = server.getRaftConf();
Collection<RaftPeer> others = conf.getOtherPeers(state.getSelfId());
final Timestamp t = new Timestamp().addTimeMs(-server.getMaxTimeoutMs());
placeHolderIndex = raftLog.getNextIndex();
senders = new SenderList(others.stream().map(
p -> server.newLogAppender(this, p, t, placeHolderIndex, true))
.toArray(LogAppender[]::new));
voterLists = divideFollowers(conf);
}
示例14: testTimedInvokeAny3
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的package包/类
/**
* timed invokeAny(c) throws NPE if c has null elements
*/
public void testTimedInvokeAny3() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
final ExecutorService e =
new CustomTPE(2, 2,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<>();
l.add(latchAwaitingStringTask(latch));
l.add(null);
try {
e.invokeAny(l, randomTimeout(), MILLISECONDS);
shouldThrow();
} catch (NullPointerException success) {}
latch.countDown();
}
}
示例15: call
import java.util.concurrent.ArrayBlockingQueue; //导入依赖的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();
}