Java异步调用目标输出的方法
假设我有一个名为Java异步调用目标输出的方法,java,asynchronous,Java,Asynchronous,假设我有一个名为check的阻塞方法,如下所示: boolean check(String input) {} 它将根据输入进行一些检查并返回决策 现在我想对输入列表异步运行这个检查,我想在一个输入通过检查后立即返回主线程,这样我就不必等待所有异步调用完成。等待所有线程完成的唯一一种情况是没有通过检查的输入。使用输入列表异步运行该方法很简单,但我不确定在获得通过检查的输入的目标输出后如何返回到主线程。基本并行流将完全做到: boolean match = inputs.parallelStre
check
的阻塞方法,如下所示:
boolean check(String input) {}
它将根据输入进行一些检查并返回决策
现在我想对输入列表异步运行这个检查,我想在一个输入通过检查后立即返回主线程,这样我就不必等待所有异步调用完成。等待所有线程完成的唯一一种情况是没有通过检查的输入。使用输入列表异步运行该方法很简单,但我不确定在获得通过检查的输入的目标输出后如何返回到主线程。基本并行流将完全做到:
boolean match = inputs.parallelStream().anyMatch(input -> check(input));
如果发现某些输入与检查匹配,则提前返回匹配==true
。
如果检查了所有输入,但未匹配任何输入,match
将为false
在标准情况下,它将使用fork/join线程池。但是,通过进一步的努力,您可以避免这种情况。这里有一个非常简单的工作示例,可以实现您的要求
Future<Boolean> future = CompletableFuture.runAsync(() -> {
// Do your checks, if true, just return this future
System.out.println("I'll run in a separate thread than the main thread.");
});
// Now, you may want to block the main thread waiting for the result
while(!future.isDone()) {
// Meanwhile, you can do others stuff
System.out.println("Doing other stuff or simply waiting...");
}
// When future.isDone() returns, you will be able to retrieve the result
Boolean result = future.get();
Future-Future=CompletableFuture.runAsync(()->{
//做你的检查,如果是真的,就把这个未来还给我
println(“我将在主线程之外的单独线程中运行。”);
});
//现在,您可能想阻止主线程等待结果
而(!future.isDone()){
//同时,你可以做其他的事情
System.out.println(“做其他事情或只是等待…”);
}
//当future.isDone()返回时,您将能够检索结果
布尔结果=future.get();
看看这个例子,看看它是否有助于您:
package callrandom;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import static java.lang.System.exit;
import static java.lang.System.out;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Logger.getLogger;
import static callrandom.Randomize.gotFive;
public class CallRandom {
public static void main(String[] args){
int MAXTHREADS = 5;
List<Future<Integer>> futs = new ArrayList<>();
ExecutorService executor = newFixedThreadPool(MAXTHREADS);
ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
for (int x = 0; x < MAXTHREADS; x++) {
out.println("Run instance: " + x);
futs.add(executor.submit(new Randomize()));
}
do {
} while (!gotFive);
for (int x = 0; x < MAXTHREADS; x++) {
if (futs.get(x).isDone()) {
try {
out.println("Return from thread: " + x + " = " + futs.get(x).get());
} catch (InterruptedException | ExecutionException ex) {
getLogger(CallRandom.class.getName()).log(SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
out.println("Cancel instance: " + x + " = " + futs.get(x).cancel(true));
}
exit(0);
}
}
packallrandom;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.concurrent.ExecutionException;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Future;
导入java.util.concurrent.ThreadPoolExecutor;
导入静态java.lang.System.exit;
导入静态java.lang.System.out;
导入静态java.util.concurrent.Executors.newFixedThreadPool;
导入静态java.util.logging.Level.SEVERE;
导入静态java.util.logging.Logger.getLogger;
导入静态callrandom.Randomize.gotFive;
公共类CallRandom{
公共静态void main(字符串[]args){
int-MAXTHREADS=5;
List futs=new ArrayList();
ExecutorService executor=newFixedThreadPool(MAXTHREADS);
ThreadPoolExecutor池=(ThreadPoolExecutor)执行器;
对于(int x=0;x
…和线程:
package callrandom;
import static java.lang.System.in;
import static java.lang.System.out;
import static java.lang.Thread.currentThread;
import java.util.Scanner;
import java.util.concurrent.Callable;
public class Randomize implements Callable<Integer> {
public static volatile Boolean gotFive = false;
@Override
public Integer call() throws Exception {
return findNumber();
}
private Integer findNumber() throws InterruptedException {
int number = 0;
do {
Scanner sc = new Scanner(in);
out.println(currentThread().getName() + ": Insert a number [5 stops this threads and triggers main thread to interrupt all others]:");
number = sc.nextInt();
} while (number != 5 && !gotFive);
gotNumber();
return number;
}
public synchronized void gotNumber() {
out.println(currentThread().getName() + " got a 5!");
gotFive = true;
}
}
packallrandom;
导入静态java.lang.System.in;
导入静态java.lang.System.out;
导入静态java.lang.Thread.currentThread;
导入java.util.Scanner;
导入java.util.concurrent.Callable;
公共类Randomize实现了可调用{
public static volatile Boolean gotFive=false;
@凌驾
公共整数调用()引发异常{
返回findNumber();
}
私有整数findNumber()引发InterruptedException{
整数=0;
做{
扫描仪sc=新扫描仪(英寸);
println(currentThread().getName()+“:插入一个数字[5停止此线程并触发主线程中断所有其他线程]:”;
编号=sc.nextInt();
}while(number!=5&&!got5);
gotNumber();
返回号码;
}
公共已同步的无效编号(){
println(currentThread().getName()+“得了5分!”);
gotFive=真;
}
}
您有5个线程正在运行并等待输入。他们一直要求输入,直到你在其中任何一个输入数字5。该线程返回到主线程,主线程取消所有剩余线程。您可能需要完成一个周期,这意味着在每个线程中插入至少一个数字,线程才能确认中断请求并自行取消,尽管有时它会在未完成周期的情况下自行取消
对这个例子的一个重要评价肯定会得到赞赏,因为这是我第一次使用Callable and Future。ParallelStream上的一个操作仍在阻塞,将等待它生成的所有线程完成。这些线程是异步执行的(它们不会等待前一个线程完成),但这并不意味着整个代码都开始异步运行。来源:另请参见。是的,调用anyMatch
的线程被阻止。如果你不想要的话。Snix方法是一条可行之路。完成所有中间工作后,轮询未来(使用isDone()
)或阻塞(使用get()
)。您也可以同时使用这两种方法。启动未来,并在未来使用一个parallelStream()
来使用多个线程来检查输入。有趣的问题。你能提供一个可行的检查功能吗?