Java 有没有更有效的方法来获得“a”;“未来”;多线程过程的结果?

Java 有没有更有效的方法来获得“a”;“未来”;多线程过程的结果?,java,multithreading,future,Java,Multithreading,Future,我编写了一个程序,以这样的方式查找给定字符串:它构建所有可能的字符串(a、b、c、…、z、aa、ab),直到在输入中构建给定字符串。应用程序使用4个线程工作,当一个线程找不到字符串时,它将在未来的中返回null 我已经实现了一种存储未来的方法,这样我就可以访问它们,当线程终止时,这看起来太复杂了,但我不知道如何才能做得更好 public class StringFinderApp { private static final String BENE = "bene"; pub

我编写了一个程序,以这样的方式查找给定字符串:它构建所有可能的字符串(a、b、c、…、z、aa、ab),直到在输入中构建给定字符串。应用程序使用4个线程工作,当一个线程找不到字符串时,它将在
未来的
中返回null

我已经实现了一种存储未来的方法,这样我就可以访问它们,当线程终止时,这看起来太复杂了,但我不知道如何才能做得更好

public class StringFinderApp {

    private static final String BENE = "bene";

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        int numberOfThreads = 4;
        System.out.println("Searching for solution using " + numberOfThreads + " threads");
        ExecutorService executor = Executors.newFixedThreadPool(4);

        List<Future<String>> futures = new LinkedList<Future<String>>();
        Future<String> future = null;
        int lengthOfExpression = 1;
        while(future == null) {
            for (int i = 0; i < 4; i++) {
                futures.add(executor.submit(new StringFinder(lengthOfExpression, BENE, i + 1)));

            }
            lengthOfExpression++;
            for(Future<String> f : futures) {
                try {
                    if(f.get()!=null) {
                        future = f;
                    }
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

        }

        try {
            System.out.println("Result is: \"" + future.get() + "\"");
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        executor.shutdownNow();
        long end = System.currentTimeMillis();
        System.out.println("breaking took : " + (end - start) + " miliseconds");
        System.out.println();


    }
}
公共类StringFinderApp{
私有静态最终字符串BENE=“BENE”;
公共静态void main(字符串[]args)引发InterruptedException{
长启动=System.currentTimeMillis();
int numberOfThreads=4;
System.out.println(“使用“+numberOfThreads+”threads搜索解决方案”);
ExecutorService executor=Executors.newFixedThreadPool(4);
列表未来=新建LinkedList();
Future=null;
int lengthofeexpression=1;
while(future==null){
对于(int i=0;i<4;i++){
futures.add(executor.submit)(新StringFinder(LengthofeExpression,BENE,i+1));
}
lengthOfExpression++;
for(未来f:未来){
试一试{
如果(f.get()!=null){
未来=f;
}
}捕获(执行例外){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
试一试{
System.out.println(“结果是:\”“+future.get()+”\”);
}捕获(执行例外){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
执行者。关机现在();
long end=System.currentTimeMillis();
println(“中断时间:”+(结束-开始)+“毫秒”);
System.out.println();
}
}
结果:

结果是:“受益”
中断时间:705毫秒

我认为,
完成服务
将为您完成以下工作:

ExecutorService executor = Executors.newFixedThreadPool(4);
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
// submit 4 Tasks to completion service
for(int i=0; i<4; ++i) {
    futures.add(completionService.submit(new StringFinder(lengthOfExpression, BENE, i + 1)));
}
// non-busy wait for the first future to complete
Future<String> f = completionService.take();
// print the result from the first finished future
System.out.println("Result is \""+f.get()+"\"");
// cancel the other threads b/c we are only interested in the result of the 'first finished thread'
futures.stream()
    .filter(fut -> f != fut)
    .foreach(fut -> fut.cancel(true));
// shutdown executor
executor.shutdown();
ExecutorService executor=Executors.newFixedThreadPool(4);
CompletionService CompletionService=新的执行者CompletionService(执行者);
//向完成服务提交4项任务
对于(int i=0;i f!=fut)
.foreach(未来->未来取消(真));
//关机执行器
executor.shutdown();

您应该首先定义“更好”。您想改进什么?我正在将所有未来存储在LinkedList中,即使是空的。在每次迭代之后,我在列表中搜索一个NOTNULL元素,如果我找到它,我就得到了结果。这导致在搜索4个字母的单词时,链表中有15个空元素。对我来说,这似乎是一种过于复杂的方式,但我想不出一个更好的解决方案来使用futures。你考虑过吗?你考虑过使用a吗?@Mangos,你的列表中没有空元素,因为你存储的是尚未解决的未来结果,机器“不知道”它们将为空,只有你知道。如果您不喜欢看到和解析列表中仍然存在的空结果,您可以尝试使用
队列
,放弃不再需要的未来。