Article From:https://www.cnblogs.com/yueshutong/p/9687662.html

1.Future mode”

FuturePatterns are closely related to multithreading technology, and can be said to be an example of optimizing programs using multithreading technology.

In programming, when a program submits a request, a reply is expected. Unfortunately, the service program may be slow to process this request, for example, it may be invoked in inefficient ways such as the Internet, HTTP, or Web Service.. In the traditional single-threaded environment, the calling function is synchronous, which means that it must wait until the service program returns to the end before other processing. In Future mode, the invocation is asynchronous, and the period of time originally waiting for return may be used to handle other things in the primary invocation functionBusiness. Example program:

(1)MainImplementation of the method

mainThe method is mainly responsible for calling the Client to initiate the request and using the returned data:

public class Future {
    public static void main(String[] args) {
        Client client = new Client();
        Data data = client.request("name");
        System.out.println("The request is completed "+System.currentTimeMillis ())./ /... Here are some other tasks.System.out.println ("data:" +data.getResult ());System.out.println ("finish" +System.currentTimeMillis ());}}

(2)ClientImplementation

clientThe main implementation is to get FutureData, open the thread that constructs RealData, and return FutureData quickly after accepting the request.

public class Client {
    public Data request(String queryStr){
        FutureData futureData = new FutureData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                RealData realData =  new RealData(queryStr);
                futureData.setRealData(realData);
            }
        }).start();
        return futureData;
    }
}

(3)DataImplementation

DataIt is an interface that provides the getResult () method.

public interface Data {
    String getResult();
}

(4)FutureDataImplementation

FutureData A fast return RealData package is implemented. It is just a package, or a virtual implementation of RealData. Therefore, it can be constructed and returned very quickly. When using the getResult () method of FutureData, the program will block.Plug, wait for RealData () to be injected into the program, then use RealData’s getResult () method to return.

public class FutureData implements Data {
    private  RealData realData = null;
    private  boolean isReady = false;

    synchronized public void setRealData(RealData realData){
        if (isReady){
            return;
        }
        this.realData = realData;
        isReady = true;
        notifyAll(); //Notifies all waiting threads to continue running.}@OverrideSynchronized public String getResult () {While (! IsRe)ADY) {Try {System.out.print ("... Waiting...");Wait (); /Make the current thread wait here until it is notified and continue to run.} catch (InterruptedException E) {E.printStackTrace ();}}Return realData.result;}}

(5)RealData Implementation

RealData It is a data model that needs to be used eventually, and its construction is slow. Here, we use the sleep () function to simulate this process.

public class RealData implements Data {
    protected String result;

    public RealData(String para) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        result = "["+para+"]";
    }

    @Override
    public String getResult() {
        return result;
    }
}

Operation results:

Request completed 1537520554813... waiting...Data: [name]Get finished 1537520555890

The process of running the program is that the Main thread gets the data, but the data is still being processed, so the Main thread enters a wait state, and when the data is processed and all the waiting threads are notified, the Main thread can continue to run.

2.JDK

FuturePatterns are so common that a Future pattern implementation is built into the JDK’s concurrent package.

Example program:

public class RealData implements Callable<String> {
    private String para;

    public RealData(String para) {
        this.para = para;
    }

    @Override
    public String call() throws Exception {
        //Here is the real business logic.Try {Thread.sleep (1000);} catch (InterruptedException E) {E.printStackTrace ();}Return "[+para+"];}Public staticVoid main (String[] args) throws ExecutionException, InterruptedException {/ / from RealData to FutUreTaskFutureTask< String> futureTask = new FutureTask< String> (New RealData ("Nam")E "))/ / create a thread poolExecutorService executorService = Executors.newFixedThreadPool (1);/ / here, open the call () method of thread executing RealData.ExecutorService.submit (futureTask);System.out.pRintln ("request completion" +System.currentTimeMillis ());/ /... Here are some other operations.System.out.println ("data:")+futureTask.get ());System.out.println ("finish" +System.currentTimeMillis ());/ / start an orderlyThe closed tasks will be executed, but new tasks will not be accepted.ExecutorService.shutdown ();}}

Operation results:

Request completed 1537521833970Data: [name]Get finished 1537521834977

CallableInterface is a user-defined implementation interface. In an application, you specify the actual content and return object of FutureTask by implementing the call () method of the Callable interface.

FutureThe thread control functions provided by the interface are as follows:

//Cancel the taskBoolean cancel (Boolean mayInterruptIfRunning)/ / has it been cancelled?Boolean isCancelled ()/ / has it been completed?Boolean ISDone ()/ / get the return object.V get () throws InterruptedException, ExecutionException/ / get the return object, set the timeout time.V get (lonG timeout, TimeUnit unit)

Post Views: 1

Leave a Reply

Your email address will not be published. Required fields are marked *