我使用 Java 中的 ExecutorService 来调用带有invokeAll(). 之后,我得到了结果集future.get()。以与创建线程相同的顺序接收结果非常重要。
这是一个片段:
try {
final List threads = new ArrayList();
// create threads
for (String name : collection)
{
final CallObject object = new CallObject(name);
threads.add(object);
}
// start all Threads
results = pool.invokeAll(threads, 3, TimeUnit.SECONDS);
for (Future<String> future : results)
{
try
{
// this method blocks until it receives the result, unless there is a
// timeout set.
final String rs = future.get();
if (future.isDone())
{
// if future.isDone() …Run Code Online (Sandbox Code Playgroud) 每个方法的注释public static ExecutorService newCachedThreadPool()中的Executor类:
Threads that have not been used for sixty seconds are terminated and
removed from the **cache**.
Run Code Online (Sandbox Code Playgroud)
我想知道缓存在哪里以及它是如何工作的?因为我Collection在ThreadPoolExecutor或者它的超类中没有看到任何可能的静态变量。
Java 代码简化后如下所示:
while(someCondition)
{
SomeType a = CalcResult(param1);
SomeType b = CalcResult(param2);
SomeType c = CalcResult(param3);
// Do something with a, b and c
}
Run Code Online (Sandbox Code Playgroud)
CalcResult()很费时间。该应用程序在 SMP 系统上运行。有人试图尝试在自己的 CPU 上同时运行所有三个计算,而不是按顺序运行它们。需要并行的始终是这 3 个任务,而不是任意数量的任务(这就是算法)。每项任务可能比其他任务花费更多或更少的时间,但通常差异不会那么大 (20-30%)。
由于他们需要返回结果,我从/sf/answers/640429471/查看了执行器服务解决方案:
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() {
return 2;
}
};
Future<Integer> future = executor.submit(callable);
// future.get() returns 2
executor.shutdown();
Run Code Online (Sandbox Code Playgroud)
由于我对 Java 的经验主要是 servlet/JSP 开发,所以我没有线程方面的经验,并且不确定该代码片段是否适用于 3 个任务而不是一个任务。
如何提交3个任务,每个任务都有自己的参数值,并等待所有任务都返回计算结果,同时确保为它们创建线程不会抵消在自己的CPU上运行的优势,即是否有一个在循环开始之前创建线程一次while(),然后简单地将新的paramN线程推入循环内的每个线程,唤醒它们,并等待它们执行所有计算的方法?
下面代码中提到的每个“CompletableFuture.runAsync”都会进行一些计算,我想在每次调用“CompletableFuture.runAsync”时获得结果。或者换句话说,我希望每个“future0,future1,future2,future3”都包含每次调用“CompletableFuture.runAsync”的结果
我怎样才能做到这一点。
*更新:
我的要求是,对于 CompletableFuture.runAsync 的每次调用,我都会进行一些计算,并且应该返回这些值的 ArrayList。在对 CompletableFuture.runAsync 的四次调用之后,我想对返回的 ArrayLists 进行一些进一步的计算。
代码:
if (this.laplaceImgList != null) {
if (!this.laplaceImgList.isEmpty()) {
if (this.laplaceImgList.size() == 3) {
//executor
ExecutorService orintMapExe;
CompletableFuture<Void> future0 = null;
CompletableFuture<Void> future1 = null;
CompletableFuture<Void> future2 = null;
CompletableFuture<Void> future3 = null;
orintMapExe = Executors.newFixedThreadPool(1);
future0 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_ZERO , this.laplaceImgList), orintMapExe);
future1 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_45 , this.laplaceImgList), orintMapExe);
future2 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_90 , this.laplaceImgList), orintMapExe);
future2 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_135 , this.laplaceImgList), orintMapExe);
CompletableFuture.allOf(future0,future1,future2,future3).join();//blocks the main …Run Code Online (Sandbox Code Playgroud) java multithreading executorservice countdownlatch threadpool
在 ExecutorCompletionService 中,我们有 take() 和 poll()。一个阻塞,直到队列有一个未来,如果队列中没有未来,另一个返回 null。但是什么时候使用 take() 和 poll() 。是否有任何特殊条件来决定这一点,或者我们可以选择任何一个??
这是我使用Future的代码片段.
import java.util.concurrent.*;
import java.util.*;
public class FutureDemo{
public FutureDemo(){
/* Future */
ExecutorService service = Executors.newFixedThreadPool(2);
for ( int i=0; i<10; i++){
MyCallable myCallable = new MyCallable((long)i);
Future<Long> futureResult = service.submit(myCallable);
Long result = null;
try{
result = futureResult.get(5000, TimeUnit.MILLISECONDS);
}catch(TimeoutException e){
System.out.println("Time out after 5 seconds");
futureResult.cancel(true);
}catch(InterruptedException ie){
System.out.println("Error: Interrupted");
}catch(ExecutionException ee){
System.out.println("Error: Execution interrupted");
}
System.out.println("Result:"+result);
}
}
public static void main(String args[]){
FutureDemo fc = new FutureDemo();
}
class MyCallable implements Callable{
Long id = …Run Code Online (Sandbox Code Playgroud) 我想使用一个ExecutorService使用单线程的。现在我插入请求(通过提交)的速率高于该线程可以处理的速率。会发生什么?
我特别想知道:
(当然,我可以假设可能会使用某些队列;并且 Oracle 实现只是“做正确的事情”;但我实际上想知道是否有真正的“规范”某处可以确定预期的行为)
我想确保我的类(更新程序服务)的所有方法都在 的线程内调用ExecutorService(假设甚至只有一个线程)。未给出方法的顺序,因此那些公共方法可能会从 的Executor线程和其他一些线程(主要是 GUI 线程)调用。
我的代码:
// Instantiated lazy using synchronized getter - I decided not to bother with shared locks
private ExecutorService executor;
/**
* Provides compatibility between calls from executor thread pool and other threads.
* No matter the thread from which you call this method, the callback will be executed
* within the loop. Proper events will be raised in the loop thread as well, so
* mind to use SwingUtilities.invokeLater if event …Run Code Online (Sandbox Code Playgroud) 使用时是否可以超时任务ThreadPoolTaskExecutor?我无法将 更改ThreadPoolTaskExecutor 为ThreadPoolExecutor或ExecutorService。
public void test() {
List<Integer> integers = new ArrayList<>();
for(int i = 0; i < 1000; i++) {
integers.add(i);
}
Map<Integer, Integer> cache = new ConcurrentHashMap<>();
ExecutorService pool = new ForkJoinPool(10);
try {
pool.submit(() -> integers.parallelStream().forEach(integer -> {
String name = Thread.currentThread().getName();
System.out.println("Foo " + name);
cache.put(integer, integer);
})).get();
} catch (Exception e) {
}
System.out.println(cache);
}
Run Code Online (Sandbox Code Playgroud)
我读到您将需要具有 volatile 变量以确保对变量的更新可预测地传播到其他线程。http://tutorials.jenkov.com/java-concurrency/volatile.html#variable-visibility-problems
在这个测试方法中,我不能将“缓存”并发哈希图声明为“易失性”变量,因为它是一个局部变量而不是一个实例变量。当代码到达 System.out.println(cache) 行时,它是否能保证我的主线程会看到 ExecutorService 线程添加到“缓存”的所有值?
executorservice ×10
java ×10
threadpool ×2
callable ×1
concurrency ×1
executor ×1
invoke ×1
java-8 ×1
java-stream ×1