java.util.concurrent.ExecutorService.shutdown()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(7.8k)|赞(0)|评价(0)|浏览(114)

本文整理了Java中java.util.concurrent.ExecutorService.shutdown()方法的一些代码示例,展示了ExecutorService.shutdown()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ExecutorService.shutdown()方法的具体详情如下:
包路径:java.util.concurrent.ExecutorService
类名称:ExecutorService
方法名:shutdown

ExecutorService.shutdown介绍

[英]Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

This method does not wait for previously submitted tasks to complete execution. Use #awaitTerminationto do that.
[中]启动有序关机,执行以前提交的任务,但不接受新任务。如果调用已经关闭,则调用没有其他效果。
此方法不会等待以前提交的任务完成执行。使用#waiting termination完成此操作。

代码示例

canonical example by Tabnine

public void runThreadTask() {
 ExecutorService service = Executors.newCachedThreadPool();
 service.execute(
   () -> {
    // ... do something inside runnable task
   });
 service.shutdown();
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
  * Stops the pool of workers.
  * 
  * @throws InterruptedException if interrupted while stopping pool of workers.
  */
 @Override
 public void stop() throws InterruptedException {
  executorService.shutdown();
  executorService.awaitTermination(4, TimeUnit.SECONDS);
 }
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * Stops logging clients. This is a blocking call.
 */
public void stop() {
 service.shutdown();
 if (!service.isTerminated()) {
  service.shutdownNow();
  try {
   service.awaitTermination(1000, TimeUnit.SECONDS);
  } catch (InterruptedException e) {
   LOGGER.error("exception awaiting termination", e);
  }
 }
 LOGGER.info("Logging clients stopped");
}

代码示例来源:origin: square/okhttp

private void parallelDrainQueue(int threadCount) {
 ExecutorService executor = Executors.newFixedThreadPool(threadCount);
 for (int i = 0; i < threadCount; i++) {
  executor.execute(new NamedRunnable("Crawler %s", i) {
   @Override protected void execute() {
    try {
     drainQueue();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }
 executor.shutdown();
}

代码示例来源:origin: stackoverflow.com

final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
 producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

代码示例来源:origin: PipelineAI/pipeline

@AfterClass
public static void tearDown() {
  threadPool.shutdown();
  try {
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
  } catch (InterruptedException ie) {
    System.out.println("Thread pool never terminated in HystrixRollingPercentileTest");
  }
}

代码示例来源:origin: stackoverflow.com

final ExecutorService pool = Executors.newFixedThreadPool(2);
final List<? extends Callable<String>> callables = Arrays.asList(
  new SleepingCallable("quick", 500),
  new SleepingCallable("slow", 5000));
try {
 for (final Future<String> future : pool.invokeAll(callables)) {
  System.out.println(future.get());
 }
} catch (ExecutionException | InterruptedException ex) { }
pool.shutdown();

代码示例来源:origin: LeonardoZ/java-concurrency-patterns

private void initialize() {
  System.out.println("=== Initializing Resources ===");
  ExecutorService executor = Executors.newFixedThreadPool(3);
  executor.execute(initResource1);
  executor.execute(initResource2);
  executor.execute(initResource3);
  executor.shutdown();
}

代码示例来源:origin: square/okhttp

public void run() throws IOException {
 try {
  long count = getTestCount();
  System.out.println("Test count: " + count);
  for (long number = 1; number <= count; number++) {
   runTest(number, count);
  }
  updateReports();
 } finally {
  client.dispatcher().executorService().shutdown();
 }
}

代码示例来源:origin: neo4j/neo4j

@Deprecated
  public static <T> Future<T> future( final Callable<T> task )
  {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<T> future = executor.submit( task );
    executor.shutdown();
    return future;
  }
}

代码示例来源:origin: stackoverflow.com

ExecutorService service = Executors.newSingleThreadExecutor();

try {
  Runnable r = new Runnable() {
    @Override
    public void run() {
      // Database task
    }
  };

  Future<?> f = service.submit(r);

  f.get(2, TimeUnit.MINUTES);     // attempt the task for two minutes
}
catch (final InterruptedException e) {
  // The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
  // Took too long!
}
catch (final ExecutionException e) {
  // An exception from within the Runnable task
}
finally {
  service.shutdown();
}

代码示例来源:origin: stackoverflow.com

ExecutorService exec = Executors.newFixedThreadPool(SOME_NUM_OF_THREADS);
try {
  for (final Object o : list) {
    exec.submit(new Runnable() {
      @Override
      public void run() {
        // do stuff with o.
      }
    });
  }
} finally {
  exec.shutdown();
}

代码示例来源:origin: stackoverflow.com

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
 taskExecutor.execute(new MyTask());
}
taskExecutor.shutdown();
try {
 taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
 ...
}

代码示例来源:origin: robolectric/robolectric

private static void shutdownDbExecutor(ExecutorService executorService, Collection<SQLiteConnection> connections) {
 for (final SQLiteConnection connection : connections) {
  getFuture("close connection on reset", executorService.submit(new Callable<Void>() {
   @Override
   public Void call() throws Exception {
    connection.dispose();
    return null;
   }
  }));
 }
 executorService.shutdown();
 try {
  executorService.awaitTermination(30, TimeUnit.SECONDS);
 } catch (InterruptedException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testMultithreadedXmlParsing() throws InterruptedException, ExecutionException {
 Callable<Configuration> parserTask = () -> new XmlConfiguration(XmlConfigurationTest.class.getResource("/configs/one-cache.xml"));
 ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
 try {
  for (Future<Configuration> c : service.invokeAll(nCopies(10, parserTask))) {
   assertThat(c.get(), IsNull.notNullValue());
  }
 } finally {
  service.shutdown();
 }
}

代码示例来源:origin: org.testng/testng

public List<FutureType> submitTasksAndWait(List<? extends Callable<FutureType>> tasks) {

  List<Future<FutureType>> takes = Lists.newArrayList(tasks.size());
  for (Callable<FutureType> callable : tasks) {
   takes.add(m_completionService.submit(callable));
  }

  List<FutureType> result = Lists.newArrayList(takes.size());
  for (Future<FutureType> take : takes) {
   try {
    result.add(take.get());
   } catch (InterruptedException | ExecutionException e) {
    throw new TestNGException(e);
   }
  }

  m_executor.shutdown();
  return result;
 }
}

代码示例来源:origin: stackoverflow.com

ExecutorService pool = Executors.newFixedThreadPool(10);
for (String name : fileNames) {
  pool.submit(new DownloadTask(name, toPath));
}
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// all tasks have now finished (unless an exception is thrown above)

代码示例来源:origin: ReactiveX/RxJava

@Override
public void run() {
  try {
    System.out.println("running TestMultiThreadedObservable thread");
    for (final String s : values) {
      threadPool.execute(new Runnable() {
    threadPool.shutdown();
  } catch (Throwable e) {
    throw new RuntimeException(e);
    threadPool.awaitTermination(2, TimeUnit.SECONDS);
  } catch (InterruptedException e) {
    throw new RuntimeException(e);

代码示例来源:origin: stackoverflow.com

final ExecutorService pool = Executors.newFixedThreadPool(2);
final CompletionService<String> service = new ExecutorCompletionService<String>(pool);
final List<? extends Callable<String>> callables = Arrays.asList(
  new SleepingCallable("slow", 5000),
  new SleepingCallable("quick", 500));
for (final Callable<String> callable : callables) {
 service.submit(callable);
}
pool.shutdown();
try {
 while (!pool.isTerminated()) {
  final Future<String> future = service.take();
  System.out.println(future.get());
 }
} catch (ExecutionException | InterruptedException ex) { }

代码示例来源:origin: ReactiveX/RxJava

final int NUM_RETRIES = Flowable.bufferSize() * 2;
int ncpu = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 2));
try {
  for (int r = 0; r < NUM_LOOPS; r++) {
    if (r % 10 == 0) {
      System.out.println("testRetryWithBackpressureParallelLoop -> " + r);
  exec.shutdown();

相关文章