


An example analysis of how Java uses future to obtain multi-threaded running results in a timely manner
In Java programming, sometimes it is necessary to obtain the running results of threads in time. This article will introduce to you through a relevant example how Java uses future to obtain the running results of threads in time. Friends who need it can refer to it.
The Future interface is part of the Java standard API and is in the java.util.concurrent package. The Future interface is an implementation of the Java thread Future mode and can be used for asynchronous calculations.
With Future, you can perform three-stage programming: 1. Start multi-threaded tasks 2. Process other things 3. Collect multi-threaded task results. This achieves non-blocking task calling. I encountered a problem on the way, that is, although the result can be obtained asynchronously, the result of the Future needs to be judged through isdone to determine whether there is a result, or the get() function can be used to obtain the execution result in a blocking manner. In this way, the result status of other threads cannot be tracked in real time, so you should use it with caution when using get directly. It is best to use it in conjunction with isdone.
Here is a better way to obtain the results of any thread in a timely manner: use CompletionService, which adds a blocking queue internally to obtain the value in the future. , and then perform corresponding processing based on the return value. The two test cases for general future use and CompletionService use are as follows:
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * 多线程执行,异步获取结果 * * @author i-clarechen * */ public class AsyncThread { public static void main(String[] args) { AsyncThread t = new AsyncThread(); List<Future<String>> futureList = new ArrayList<Future<String>>(); t.generate(3, futureList); t.doOtherThings(); t.getResult(futureList); } /** * 生成指定数量的线程,都放入future数组 * * @param threadNum * @param fList */ public void generate(int threadNum, List<Future<String>> fList) { ExecutorService service = Executors.newFixedThreadPool(threadNum); for (int i = 0; i < threadNum; i++) { Future<String> f = service.submit(getJob(i)); fList.add(f); } service.shutdown(); } /** * other things */ public void doOtherThings() { try { for (int i = 0; i < 3; i++) { System.out.println("do thing no:" + i); Thread.sleep(1000 * (new Random().nextInt(10))); } } catch (InterruptedException e) { e.printStackTrace(); } } /** * 从future中获取线程结果,打印结果 * * @param fList */ public void getResult(List<Future<String>> fList) { ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(getCollectJob(fList)); service.shutdown(); } /** * 生成指定序号的线程对象 * * @param i * @return */ public Callable<String> getJob(final int i) { final int time = new Random().nextInt(10); return new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(1000 * time); return "thread-" + i; } }; } /** * 生成结果收集线程对象 * * @param fList * @return */ public Runnable getCollectJob(final List<Future<String>> fList) { return new Runnable() { public void run() { for (Future<String> future : fList) { try { while (true) { if (future.isDone() && !future.isCancelled()) { System.out.println("Future:" + future + ",Result:" + future.get()); break; } else { Thread.sleep(1000); } } } catch (Exception e) { e.printStackTrace(); } } } }; } }
The running results are printed in the same order as when the future is put into the list, which is 0, 1, 2:
do thing no:0 do thing no:1 do thing no:2 Future:java.util.concurrent.FutureTask@68e1ca74,Result:thread-0 Future:java.util.concurrent.FutureTask@3fb2bb77,Result:thread-1 Future:java.util.concurrent.FutureTask@6f31a24c,Result:thread-2
The following is the solution for the thread that finishes execution first:
import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; public class testCallable { public static void main(String[] args) { try { completionServiceCount(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } /** * 使用completionService收集callable结果 * @throws ExecutionException * @throws InterruptedException */ public static void completionServiceCount() throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>( executorService); int threadNum = 5; for (int i = 0; i < threadNum; i++) { completionService.submit(getTask(i)); } int sum = 0; int temp = 0; for(int i=0;i<threadNum;i++){ temp = completionService.take().get(); sum += temp; System.out.print(temp + "\t"); } System.out.println("CompletionService all is : " + sum); executorService.shutdown(); } public static Callable<Integer> getTask(final int no) { final Random rand = new Random(); Callable<Integer> task = new Callable<Integer>() { @Override public Integer call() throws Exception { int time = rand.nextInt(100)*100; System.out.println("thead:"+no+" time is:"+time); Thread.sleep(time); return no; } }; return task; } }
The running result is that the result of the thread that ends first is processed first:
thead:0 time is:4200 thead:1 time is:6900 thead:2 time is:2900 thead:3 time is:9000 thead:4 time is:7100 0 1 4 3 CompletionService all is : 10
Summary
The above is the detailed content of An example analysis of how Java uses future to obtain multi-threaded running results in a timely manner. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
