Calling method:
/** * Number of clicks/month (year) Callable */ public void yearlyClickCallable() { // Get parameters String year = getPara("year"); // Statistics data set X List<String> xList = new ArrayList<String>(); xList.add("January"); xList.add("February"); xList.add("March"); xList.add("April"); xList.add("May"); xList.add("June"); xList.add("July"); xList.add("July"); xList.add("August"); xList.add("September"); xList.add("October"); xList.add("November"); xList.add("December"); // Statistics dataset Y List<Integer> yList = new ArrayList<Integer>(); // Receive thread value List<Future<List<Map<String, Object>>>>>>> futureList = new ArrayList<Future<List<Map<String, Object>>>>(); // Counter int count = 0; // Create a thread pool (decide how many threads to start) ExecutorService pool = Executors.newCachedThreadPool(); // Monthly log analysis for (int m = 1; m <= 12; m++) { // Collect date parameters List<String> dateList = new ArrayList<String>(); // String date = ""; // Determine how many days int days = CalendarUtil.weekForMonth(Integer.valueOf(year), m); // Combination date for (int i = 1; i <= days; i++) { if (i <= 9) { if (m <= 9) { date = year + "-0" + m + "-0" + i; } else { date = year + "-" + m + "-0" + i; } } else { if (m <= 9) { date = year + "-0" + m + "-" + i; } else { date = year + "-" + m + "-" + i; } } dateList.add(date); } // Start Future<List<Map<String, Object>>> future = pool.submit(new ReadLogFileCallableByYear(dateList)); futureList.add(future); } // Close the thread pool pool.shutdown(); // Receive the result set for (Future<List<Map<String, Object>>>> future : futureList) { try { // Receive the parameter List<Map<String, Object>>> list = future.get(1, TimeUnit.SECONDS); // Set the parameter for (int p = 0; p < list.size(); p++) { count += (int) list.get(p).get("clickCount"); if (list.get(p).get("month").equals("01")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("02")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("03")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("03")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("03")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("04")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("05")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("06")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("06")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("06")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("07")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("08")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("09")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("09")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("09")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("10")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("11")) { yList.add((Integer) list.get(p).get("clickCount")); } else if (list.get(p).get("month").equals("12")) { yList.add((Integer) list.get(p).get("clickCount")); } } } } catch (Exception e) { e.printStackTrace(); } } setAttr("totalCount", count); setAttr("x", xList); setAttr("y", yList); renderJson(); }Multithreaded method:
package com.ninemax.util.loganalysis;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.Callable;import com.ninemax.util.loganalysis.tool.ConstantUtil;/** * Multithreaded return value* * @author Darker * */public class ReadLogFileCallableByYear implements Callable<List<Map<String, Object>>> { // Date array private List<String> clickDate; // Return result set public List<Map<String, Object>>> list = new ArrayList<Map<String, Object>>(); public ReadLogFileCallableByYear(List<String> clickDate) { this.clickDate = clickDate; } @Override public List<Map<String, Object>> call() throws Exception { // Receive parameters Map<String, Object> map = new HashMap<String, Object>(); // Use FileInputStream to read file information FileInputStream fis = null; // Use InputStreamReader to transcode InputStreamReader reader = null; // Use BufferedReader to buffer BufferedReader bufReader = null; // Use StringBuffer to receive file content container StringBuffer buf = new StringBuffer(); // Clicks/month int monthClick = 0; for (int i = 0; i < clickDate.size(); i++) { // Get file File clickLogFile = new File(ConstantUtil.LOGLOCATION, "article.click."+ clickDate.get(i) + ".txt"); // Determine whether the file exists if (!clickLogFile.exists() || clickLogFile.isDirectory()) { System.err.println(clickDate.get(i) + "The file does not exist..."); map.put("month", clickDate.get(i).substring(5, 7)); map.put("clickCount", 0); list.add(map); return list; } else { try { // Node stream fis = new FileInputStream(clickLogFile); // Convert stream reader = new InputStreamReader(fis, "utf-8"); // Processing stream bufReader = new BufferedReader(reader); // Counter int count = 0; // Read String line = ""; // Read file while ((line = bufReader.readLine()) != null) { // Count count++; // Receive data if (!line.equals(null) && !line.equals("")) { buf.append(line + "/n"); } } if (count == 0) { count = 0; } else { count = count - 1; } monthClick += count; } catch (Exception e) { e.printStackTrace(); } finally { // Close stream try { bufReader.close(); reader.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } // Result set map.put("month", clickDate.get(0).substring(5, 7)); if (monthClick == 0) { map.put("clickCount", 0); } else { map.put("clickCount", monthClick); } list.add(map); return list; }}I will share with you an example of a netizen, which is also very good
import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * Callable and Future interfaces* Callable are interfaces similar to Runnable. Classes that implement Callable interface and classes that implement Runnable are tasks that can be executed by other threads. * Callable and Runnable have several differences: * (1) The method specified by Callable is call(), while the method specified by Runnable is run(). * (2) The callable task can return the value after it is executed, while the Runnable task cannot return the value. * (3) The call() method can throw exceptions, while the run() method cannot throw exceptions. * (4) Run the Callable task and you can get a Future object. Future represents the result of asynchronous calculation. * It provides a method to check whether the calculation is completed, to wait for the calculation to be completed, and to retrieve the results of the calculation. * Through the Future object, you can understand the task execution status, cancel the task execution, and also obtain the results of the task execution. */public class CallableAndFuture {/** * Customize a task class to implement the Callable interface*/public static class MyCallableClass implements Callable {// Flag bit private int flag = 0;public MyCallableClass(int flag) {this.flag = flag;}public String call() throws Exception {if (this.flag == 0) {// If the value of flag is 0, return immediately "flag = 0";}if (this.flag == 1) {// If the value of flag is 1, make an infinite loop try {while (true) {System.out.println("looping...");Thread.sleep(2000);}} catch (InterruptedException e) {System.out.println("Interrupted");}return "false";} else {// Falg is not 0 or 1, then an exception is thrown. new Exception("Bad flag value!");}}} public static void main(String[] args) {// Define 3 Callable types tasks MyCallableClass task1 = new MyCallableClass(0);MyCallableClass task2 = new MyCallableClass(1);MyCallableClass task3 = new MyCallableClass(2);// Create a service that executes the task ExecutorService es = Executors.newFixedThreadPool(3);try {// Submit and execute the task. A Future object is returned when the task is started. // If you want to get the result of the task execution or an exception, you can operate the Future object. Future future1 = es.submit(task1);// Get the result of the first task. If the get method is called, the current thread will wait for the task to be executed before executing System.out.println("task1: " + future1.get());Future future2 = es.submit(task2);// Wait for 5 seconds before stopping the second task. Because the second task is an infinite loop Thread.sleep(5000);System.out.println("task2 cancel: " + future2.cancel(true));// Get the output of the third task, because executing the third task will cause an exception // So the following statement will cause an exception to throw Future future3 = es.submit(task3);System.out.println("task3: " + future3.get());} catch (Exception e) {System.out.println(e.toString());}// Stop the task execution service es.shutdownNow();}}The above is the entire content of this article. If you need it, please refer to it.