相关疑难解决方法(0)

Java 8并行流中的自定义线程池

是否可以为Java 8 并行流指定自定义线程池?我找不到任何地方.

想象一下,我有一个服务器应用程序,我想使用并行流.但是应用程序很大且是多线程的,因此我想将它划分为区分.我不想在另一个模块的应用程序块任务的一个模块中执行缓慢的任务.

如果我不能为不同的模块使用不同的线程池,这意味着我无法在大多数现实情况下安全地使用并行流.

请尝试以下示例.在单独的线程中执行一些CPU密集型任务.这些任务利用并行流.第一个任务被破坏,因此每个步骤需要1秒(通过线程休眠模拟).问题是其他线程卡住并等待损坏的任务完成.这是一个人为的例子,但想象一下servlet应用程序和有人向共享fork连接池提交长时间运行的任务.

public class ParallelTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();

        es.execute(() -> runTask(1000)); //incorrect task
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));


        es.shutdown();
        es.awaitTermination(60, TimeUnit.SECONDS);
    }

    private static void runTask(int delay) {
        range(1, 1_000_000).parallel().filter(ParallelTest::isPrime).peek(i -> Utils.sleep(delay)).max()
                .ifPresent(max -> System.out.println(Thread.currentThread() + " " + max));
    }

    public static boolean isPrime(long n) {
        return n > 1 && rangeClosed(2, (long) sqrt(n)).noneMatch(divisor …
Run Code Online (Sandbox Code Playgroud)

java parallel-processing concurrency java-8 java-stream

371
推荐指数
9
解决办法
15万
查看次数

等待未来的名单

我有一个返回List期货的方法

List<Future<O>> futures = getFutures();
Run Code Online (Sandbox Code Playgroud)

现在我想要等到所有期货都成功处理完成,或者将来输出的任何任务抛出异常.即使一个任务抛出异常,也没有必要等待其他期货.

简单的方法是

wait() {

   For(Future f : futures) {
     try {
       f.get();
     } catch(Exception e) {
       //TODO catch specific exception
       // this future threw exception , means somone could not do its task
       return;
     }
   }
}
Run Code Online (Sandbox Code Playgroud)

但问题是,例如,如果第四个未来抛出异常,那么我将不必要地等待前3个期货可用.

怎么解决这个?会以任何方式倒数闩锁帮助吗?我无法使用Future,isDone因为java doc说

boolean isDone()
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.
Run Code Online (Sandbox Code Playgroud)

java multithreading future

119
推荐指数
4
解决办法
13万
查看次数

ExecutorService 具有大量任务

我有一个文件列表和一个分析这些文件的分析器列表。文件数量可能很大(200,000 个),分析器数量可能很大(1000 个)。因此操作总数可能非常大(200,000,000)。现在,我需要应用多线程来加快速度。我遵循了这种方法:

ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (File file : listOfFiles) {
  for (Analyzer analyzer : listOfAnalyzers){
    executor.execute(() -> {
      boolean exists = file.exists();
      if(exists){
        analyzer.analyze(file);
      }
    });
  }
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

但这种方法的问题是它从内存中获取了太多内容,我想有更好的方法来做到这一点。我还是java和多线程的初学者。

java multithreading executorservice threadpool

2
推荐指数
1
解决办法
2130
查看次数