Application scenarios
Financial costing. There may be multiple time-consuming steps. If sequential execution is very slow. In the case of mutual data acquisition without data dependence, Future can be used to execute in parallel
public class FutureTest implements Callable<BigDecimal> { private String sqlQueryStr; public FutureTest(String sqlQueryStr) { this.sqlQueryStr=sqlQueryStr; } @Override public BigDecimal call() throws Exception { // TODO Auto-generated method stub System.out.println(sqlQueryStr+"Query database to get data" ); return new BigDecimal(3 ); } public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService=Executors.newFixedThreadPool(2); FutureTask<BigDecimal> futureTask=new FutureTask<BigDecimal>(new FutureTest("进货列表sql")); FutureTask<BigDecimal> futureTask2=new FutureTask<BigDecimal>(new FutureTest("销售列表sql")); Future future= executorService.submit(futureTask); executorService.execute(futureTask2); BigDecimal money1=futureTask.get(); BigDecimal money2=futureTask.get();
/** * The difference between submit and execute * submit has a return value execute no * The return value of submit can execute cancel to execute the cancellation operation or judge whether the execution ends by calling get if it is equal to null */ }
Implement future asynchronous loading by yourself
public class SimpleReusltData { boolean state = false; String data; public synchronized String getData() throws InterruptedException { // If the data is not retrieved, wait if (! state) { wait(); // Release the lock. wait for wakeup } return data; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } public synchronized void setData(String data) { System.out.println( "Executed" ); this .notify(); // Do not release the lock after execution and release the lock this .state= true ; this .data = data; } }
public class RequestUtils{ public static SimpleReusltData get(String url) { final SimpleReusltData simpleReusltData=new SimpleReusltData(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { // Simulate execution of http time-consuming operation Thread.sleep(3000 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } simpleReusltData.setData( "Data" ); } }).start(); return simpleReusltData; } public static void main(String[] args) throws InterruptedException { SimpleReusltData simpleReusltData=RequestUtils.get("url"); System.out.println(simpleReusltData.getData()); } }
If the getData method is called, if there is no setData, the state is false, then the lock is released, and the lock is added to the waiting queue.