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


Java Future.cancel方法代码示例

本文整理汇总了Java中java.util.concurrent.Future.cancel方法的典型用法代码示例。如果您正苦于以下问题:Java Future.cancel方法的具体用法?Java Future.cancel怎么用?Java Future.cancel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.Future的用法示例。


在下文中一共展示了Future.cancel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: shutdownAndCancelTask

import java.util.concurrent.Future; //导入方法依赖的package包/类
private static void shutdownAndCancelTask(ExecutorService execService, int shutdownDelaySec, String name, Future future) {
    try {
        execService.shutdown();
        System.out.println("Waiting for " + shutdownDelaySec + " sec before shutting down service...");
        execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
    } catch (Exception ex) {
        System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
    } finally {
        if (!execService.isTerminated()) {
            System.out.println("Terminating remaining running tasks...");
            if (future != null && !future.isDone() && !future.isCancelled()) {
                System.out.println("Cancelling task " + name + "...");
                future.cancel(true);
            }
        }
        System.out.println("Calling execService.shutdownNow()...");
        List<Runnable> l = execService.shutdownNow();
        System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Cookbook,代码行数:21,代码来源:Chapter07Concurrency03.java

示例2: testDrainTimesOut

import java.util.concurrent.Future; //导入方法依赖的package包/类
private void testDrainTimesOut(BlockingQueue<Object> q) throws Exception {
  for (boolean interruptibly : new boolean[] {true, false}) {
    assertEquals(0, Queues.drain(q, ImmutableList.of(), 1, 10, MILLISECONDS));

    Producer producer = new Producer(q, 1);
    // producing one, will ask for two
    Future<?> producerThread = threadPool.submit(producer);
    producer.beganProducing.await();

    // make sure we time out
    Stopwatch timer = Stopwatch.createStarted();

    int drained = drain(q, newArrayList(), 2, 10, MILLISECONDS, interruptibly);
    assertThat(drained).isAtMost(1);

    assertThat(timer.elapsed(MILLISECONDS)).isAtLeast(10L);

    // If even the first one wasn't there, clean up so that the next test doesn't see an element.
    producerThread.cancel(true);
    producer.doneProducing.await();
    if (drained == 0) {
      q.poll(); // not necessarily there if producer was interrupted
    }
  }
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:26,代码来源:QueuesTest.java

示例3: sendEzspTransaction

import java.util.concurrent.Future; //导入方法依赖的package包/类
/**
 * Sends an EZSP request to the NCP and waits for the response. The response is correlated with the request and the
 * returned {@link EzspFrame} contains the request and response data.
 *
 * @param ezspTransaction
 *            Request {@link EzspFrame}
 * @return response {@link EzspFrame}
 */
public EzspTransaction sendEzspTransaction(EzspTransaction ezspTransaction) {
    Future<EzspFrame> futureResponse = sendEzspRequestAsync(ezspTransaction);
    if (futureResponse == null) {
        logger.debug("Error sending EZSP transaction: Future is null");
        return null;
    }

    try {
        futureResponse.get();
        return ezspTransaction;
    } catch (InterruptedException | ExecutionException e) {
        futureResponse.cancel(true);
        logger.debug("EZSP interrupted in sendRequest: ", e);
    }

    return null;
}
 
开发者ID:zsmartsystems,项目名称:com.zsmartsystems.zigbee,代码行数:26,代码来源:AshFrameHandler.java

示例4: timedVirtualMachineCreation

import java.util.concurrent.Future; //导入方法依赖的package包/类
VirtualMachine timedVirtualMachineCreation(Callable<VirtualMachine> creator,
        Callable<Integer> processComplete) throws Exception {
    VirtualMachine result;
    ExecutorService executor = Executors.newCachedThreadPool(runnable -> {
        Thread thread = Executors.defaultThreadFactory().newThread(runnable);
        thread.setDaemon(true);
        return thread;
    });
    try {
        Future<VirtualMachine> future = executor.submit(creator);
        if (processComplete != null) {
            executor.submit(() -> {
                Integer i = processComplete.call();
                future.cancel(true);
                return i;
            });
        }

        try {
            result = future.get(connectTimeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            future.cancel(true);
            throw ex;
        }
    } finally {
        executor.shutdownNow();
    }
    return result;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:JdiInitiator.java

示例5: cancelCleanup

import java.util.concurrent.Future; //导入方法依赖的package包/类
private boolean cancelCleanup()
{
	final Future<?> task = _cleanupTask;
	if (task != null)
	{
		_cleanupTask = null;
		return task.cancel(true);
	}
	return false;
}
 
开发者ID:rubenswagner,项目名称:L2J-Global,代码行数:11,代码来源:L2GameClient.java

示例6: cancel

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override public void cancel() {
  canceled = true;
  Future<?> task = this.task;
  if (task != null) {
    task.cancel(true);
  }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:8,代码来源:BehaviorCall.java

示例7: decodePage

import java.util.concurrent.Future; //导入方法依赖的package包/类
public void decodePage(Object decodeKey, int pageNum, final DecodeCallback decodeCallback, float zoom, RectF pageSliceBounds)
{
    final DecodeTask decodeTask = new DecodeTask(pageNum, decodeCallback, zoom, decodeKey, pageSliceBounds);
    synchronized (decodingFutures)
    {
        if (isRecycled) {
            return;
        }
        final Future<?> future = executorService.submit(new Runnable()
        {
            public void run()
            {
                try
                {
                    Thread.currentThread().setPriority(Thread.NORM_PRIORITY-1);
                    performDecode(decodeTask);
                }
                catch (IOException e)
                {
                    Log.e(DECODE_SERVICE, "Decode fail", e);
                }
            }
        });
        final Future<?> removed = decodingFutures.put(decodeKey, future);
        if (removed != null)
        {
            removed.cancel(false);
        }
    }
}
 
开发者ID:lidong1665,项目名称:AndroidPDF,代码行数:31,代码来源:DecodeServiceBase.java

示例8: actionPerformed

import java.util.concurrent.Future; //导入方法依赖的package包/类
public void actionPerformed(ActionEvent e) {
    setEnabled(false); // discourage repeated clicking

    Future<?> actionTask;
    synchronized (this) {
        actionTask = task;
    }

    if (actionTask != null) {
        actionTask.cancel(true);
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:13,代码来源:StopAction.java

示例9: assertThrowInterruptedExceptionWhenInterrupted

import java.util.concurrent.Future; //导入方法依赖的package包/类
void assertThrowInterruptedExceptionWhenInterrupted(Action[] actions) {
    int n = actions.length;
    Future<?>[] futures = new Future<?>[n];
    CountDownLatch threadsStarted = new CountDownLatch(n);
    CountDownLatch done = new CountDownLatch(n);

    for (int i = 0; i < n; i++) {
        Action action = actions[i];
        futures[i] = cachedThreadPool.submit(new CheckedRunnable() {
            public void realRun() throws Throwable {
                threadsStarted.countDown();
                try {
                    action.run();
                    shouldThrow();
                }
                catch (InterruptedException success) {}
                catch (Throwable fail) { threadUnexpectedException(fail); }
                assertFalse(Thread.interrupted());
                done.countDown();
            }});
    }

    await(threadsStarted);
    assertEquals(n, done.getCount());
    for (Future<?> future : futures) // Interrupt all the tasks
        future.cancel(true);
    await(done);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:StampedLockTest.java

示例10: remove

import java.util.concurrent.Future; //导入方法依赖的package包/类
public void remove(P param) {
    Future<R> f = cache.get(param);

    if (f != null && !f.isDone()) {
        f.cancel(true);
    }

    cache.remove(param);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:10,代码来源:TasksCachedProcessor.java

示例11: testCannotScheduleLongerThanIntegerMaxValue

import java.util.concurrent.Future; //导入方法依赖的package包/类
public void testCannotScheduleLongerThanIntegerMaxValue() throws Exception {
    Runnable r = new Runnable() {

        @Override
        public void run() {
            fail ("Should not have been run");
        }
    };
    try {
        Future<?> f = RequestProcessor.getDefault().schedule(r, Long.MAX_VALUE, TimeUnit.DAYS);
        f.cancel(true);
    } catch (Exception e) {}
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:14,代码来源:RequestProcessor180386Test.java

示例12: cancel

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override
public void cancel() {
    super.cancel();
    if (mFutureList != null && !mFutureList.isEmpty()) {
        for (Future future : mFutureList) {
            if (future != null) {
                future.cancel(true);
            }
        }
    }
}
 
开发者ID:ghnor,项目名称:Flora,代码行数:12,代码来源:BatchCompressEngine.java

示例13: destory

import java.util.concurrent.Future; //导入方法依赖的package包/类
public void destory(Long pipelineId) {
    if (!threads.containsKey(pipelineId)) {
        throw new IllegalArgumentException("pipeline is not exist!");
    }

    Future future = threads.get(pipelineId);
    future.cancel(true);
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:9,代码来源:ExtractServiceDemo.java

示例14: maybePropagateCancellation

import java.util.concurrent.Future; //导入方法依赖的package包/类
final void maybePropagateCancellation(@Nullable Future<?> related) {
  if (related != null & isCancelled()) {
    related.cancel(wasInterrupted());
  }
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:6,代码来源:AbstractFuture.java

示例15: stop

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override
public boolean stop(String entityClassName) {
    Future<?> future = this.inFlightTasksMap.get(entityClassName);
    return future != null && future.cancel(true);
}
 
开发者ID:chaokunyang,项目名称:jkes,代码行数:6,代码来源:ForkJoinIndexer.java


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