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

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

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

ExecutorService.awaitTermination介绍

[英]Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
[中]阻塞,直到所有任务在关闭请求后完成执行,或超时发生,或当前线程中断(以先发生的为准)。

代码示例

代码示例来源: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: iluwatar/java-design-patterns

/**
 * Stops the reactor and related resources such as dispatcher.
 * 
 * @throws InterruptedException
 *           if interrupted while stopping the reactor.
 * @throws IOException
 *           if any I/O error occurs.
 */
public void stop() throws InterruptedException, IOException {
 reactorMain.shutdownNow();
 selector.wakeup();
 reactorMain.awaitTermination(4, TimeUnit.SECONDS);
 selector.close();
 LOGGER.info("Reactor stopped");
}

代码示例来源: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: iBotPeaches/Apktool

public static String execAndReturn(String[] cmd) {
  ExecutorService executor = Executors.newCachedThreadPool();
  try {
    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process process = builder.start();
    StreamCollector collector = new StreamCollector(process.getInputStream());
    executor.execute(collector);
    process.waitFor();
    if (! executor.awaitTermination(15, TimeUnit.SECONDS)) {
      executor.shutdownNow();
      if (! executor.awaitTermination(5, TimeUnit.SECONDS)) {
        System.err.println("Stream collector did not terminate.");
      }
    }
    return collector.get();
  } catch (IOException | InterruptedException e) {
    return null;
  }
}

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

/* Get an executor service that will run a maximum of 5 threads at a time: */
ExecutorService exec = Executors.newFixedThreadPool(5);
/* For all the 100 tasks to be done altogether... */
for (int i = 0; i < 100; i++) {
  /* ...execute the task to run concurrently as a runnable: */
  exec.execute(new Runnable() {
    public void run() {
      /* do the work to be done in its own thread */
      System.out.println("Running in: " + Thread.currentThread());
    }
  });
}
/* Tell the executor that after these 100 steps above, we will be done: */
exec.shutdown();
try {
  /* The tasks are now running concurrently. We wait until all work is done, 
   * with a timeout of 50 seconds: */
  boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);
  /* If the execution timed out, false is returned: */
  System.out.println("All done: " + b);
} catch (InterruptedException e) { e.printStackTrace(); }

代码示例来源: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: real-logic/aeron

@After
public void after() throws InterruptedException
{
  executor.shutdownNow();
  if (!executor.awaitTermination(5, TimeUnit.SECONDS))
  {
    System.out.println("Warning: not all tasks completed promptly");
  }
}

代码示例来源:origin: objectbox/objectbox-java

/** dump thread stacks if pool does not terminate promptly. */
private void checkThreadTermination() {
  try {
    if (!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
      int activeCount = Thread.activeCount();
      System.err.println("Thread pool not terminated in time; printing stack traces...");
      Thread[] threads = new Thread[activeCount + 2];
      int count = Thread.enumerate(threads);
      for (int i = 0; i < count; i++) {
        System.err.println("Thread: " + threads[i].getName());
        Thread.dumpStack();
      }
    }
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
}

代码示例来源: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: LeonardoZ/java-concurrency-patterns

public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newCachedThreadPool();
    // Synchronized - Vector
    Vector<Long> vec = new Vector<>();

    Runnable insertIfAbsent = () -> {
      long millis = System.currentTimeMillis() / 1000;
      insertIfAbsent(vec, millis);
    };
    for (int i = 0; i < 10001; i++) {
      executor.execute(insertIfAbsent);
    }
    executor.shutdown();
    executor.awaitTermination(4000, TimeUnit.SECONDS);

    // Using the wrappers for not sync collections
    // List<String> synchronizedList = Collections.synchronizedList(abcList);
    // Collections.synchronizedMap(m)
    // Collections.synchronizedXXX
  }
}

代码示例来源:origin: GlowstoneMC/Glowstone

/**
 * Downloads the libraries.
 */
public void run() {
  if (!directory.isDirectory() && !directory.mkdirs()) {
    GlowServer.logger
        .log(Level.SEVERE, "Could not create libraries directory: " + directory);
  }
  for (Library library : libraries) {
    downloaderService.execute(new LibraryDownloader(library));
  }
  downloaderService.shutdown();
  try {
    if (!downloaderService.awaitTermination(1, TimeUnit.MINUTES)) {
      downloaderService.shutdownNow();
    }
  } catch (InterruptedException e) {
    GlowServer.logger.log(Level.SEVERE, "Library Manager thread interrupted: ", e);
  }
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void two_concurrent_calls_to_startit_call_migration_engine_only_once() throws Exception {
 pool.submit(new CallStartit());
 pool.submit(new CallStartit());
 pool.awaitTermination(2, TimeUnit.SECONDS);
 assertThat(triggerCount.get()).isEqualTo(1);
}

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

@Test(timeout = 30000)
public void testIssue2890NoStackoverflow() throws InterruptedException {
  final ExecutorService executor = Executors.newFixedThreadPool(2);
  final Scheduler sch = Schedulers.from(executor);
  executor.awaitTermination(20000, TimeUnit.MILLISECONDS);

代码示例来源: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: Netflix/eureka

private void shutdownAndAwaitTermination(ExecutorService pool) {
  pool.shutdown();
  try {
    if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {
      pool.shutdownNow();
    }
  } catch (InterruptedException e) {
    logger.warn("InstanceInfoReplicator stop interrupted");
  }
}

代码示例来源:origin: google/guava

@Override
 public void run() {
  try {
   // We'd like to log progress and failures that may arise in the
   // following code, but unfortunately the behavior of logging
   // is undefined in shutdown hooks.
   // This is because the logging code installs a shutdown hook of its
   // own. See Cleaner class inside {@link LogManager}.
   service.shutdown();
   service.awaitTermination(terminationTimeout, timeUnit);
  } catch (InterruptedException ignored) {
   // We're shutting down anyway, so just ignore.
  }
 }
}));

代码示例来源:origin: codingapi/tx-lcn

@Bean
public ExecutorService executorService() {
  ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    executorService.shutdown();
    try {
      executorService.awaitTermination(10, TimeUnit.MINUTES);
    } catch (InterruptedException ignored) {
    }
  }));
  return executorService;
}

代码示例来源:origin: Graylog2/graylog2-server

@Override
protected void shutDown() throws Exception {
  LOG.debug("Stopping BufferSynchronizerService");
  if (cluster.isConnected() && cluster.isDeflectorHealthy()) {
    final ExecutorService executorService = executorService(metricRegistry);
    executorService.submit(new Runnable() {
      @Override
      public void run() {
        bufferSynchronizer.waitForEmptyBuffers(configuration.getShutdownTimeout(), TimeUnit.MILLISECONDS);
      }
    });
    executorService.shutdown();
    executorService.awaitTermination(configuration.getShutdownTimeout(), TimeUnit.MILLISECONDS);
  } else {
    LOG.warn("Elasticsearch is unavailable. Not waiting to clear buffers and caches, as we have no healthy cluster.");
  }
  LOG.debug("Stopped BufferSynchronizerService");
}

相关文章