Java.util.Concurrent.Futuer mode use

package com.bjsxt.height.concurrent019;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * The future mode is very suitable for processing time-consuming business logic, which can reduce the response time of the system and provide system throughput.
 * The class that does business logic processing must implement the Callable interface and override the call method.
 */
public class UseFuture implements Callable<String>{
	private String para;
	
	public UseFuture(String para){
		this.para = to;
	}
	
	/**
	 * Here is the real business logic, its execution may be slow
	 */
	@Override
	public String call() throws Exception {
		//Simulate execution time
		Thread.sleep(3000);
		String result = this.para + "processing completed";
		return result;
	}
	
	// main control function
	public static void main(String[] args) throws Exception {
		String queryStr = "query";
		//Construct FutureTask, and pass in the class that needs to be processed by business logic. This class must be a class that implements the Callable interface
		FutureTask<String> future = new FutureTask<String>(new UseFuture(queryStr));
		//Create a thread pool of fixed threads and the number of threads is 1,
		ExecutorService executor = Executors.newFixedThreadPool(1);
		//Submit the task future here, then start the thread to execute the call() method of RealData
		executor.submit(future);
		System.out.println("Request completed");
		try {
			//Additional data operations can be done here, that is, the main program executes other business logic
			System.out.println("Process other logic...");
			Thread.sleep(2000);
		} catch (Exception e) {
			e.printStackTrace ();
		}
		//Call the data acquisition method, if the call() method is not completed, it will still wait
		System.out.println("数据:" + future.get());
		executor.shutdown();
	}

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326116946&siteId=291194637