Assuming there is a very computationally expensive task that takes a long time to process with single-threaded processing, consider using multithreading to calculate data in batches and then summarize the data output. Here, the use of cyclicbarrier to achieve. The function of this class is to specify a specific number of threads, and wait until those threads have finished executing the code behind its await () method, if a thread class is set in the constructor, then the thread in the constructor is executed after the business thread executes, and then the thread behind the await method is executed.
Package Test;import Java.util.hashmap;import Java.util.map;import java.util.concurrent.BrokenBarrierException; Import Java.util.concurrent.callable;import Java.util.concurrent.cyclicbarrier;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.future;public class Test1 {private static Executorservice Service = Executors.newfixedthreadpool (4);p ublic static void Main (string[] args) {final map<string, integer> Map = n EW hashmap<string, integer> (4); Cyclicbarrier cb = new Cyclicbarrier (4, New Runnable () {public void Run () {Integer count1 = map.get ("1"); Integer count2 = m Ap.get ("2"), Integer count3 = Map.get ("3"), Integer count4 = Map.get ("4"); System.out.println ("count=" + (count1 + count2 + count3 + count4));}); New Thread (new Testthread (map, "1", cb,1000)). Start (); New Thread (New Testthread (Map, "2", cb,1000)). Start (); New Thread ( New Testthread (Map, "3", cb,1000)). Start (); New ThreaD (New Testthread (Map, "4", cb,1000)). Start ();//thread pool implementation way int sum = 0;for (int i = 0; i < 4; i++) {future<integer> dat A = Service.submit (new callable<integer> () {@Overridepublic Integer call () throws Exception {int sum = 0;for (int i = 0; i < 1000; i++) {sum + = i;} return sum;}}); try {sum + = Data.get (). Intvalue ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace () ;} catch (Executionexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} System.out.println ("count===" + Sum);}} Class Testthread implements Runnable {private map<string, integer> map;private String type;private cyclicbarrier CB ;p rivate int n;public testthread (map<string, integer> Map, String type, cyclicbarrier cb, int n) {this.map = Map;thi S.type =TYPE;THIS.CB = CB;THIS.N = n;} @Overridepublic void Run () {int sum = 0;for (int i = 0; i < n; i++) {sum + = i;} Map.put (type, sum); try {cb.await ();} catch (Interruptedexception e) {//TODO auto-generated catchBlocke.printstacktrace ();} catch (Brokenbarrierexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Multithreading the data and then merging the data