Thread 2---Async 1

Source: Internet
Author: User
Tags ticket

What is synchronization in Java? What is async? We have to be clear about these two concepts. Only by defining these two concepts can you explicitly use synchronous and asynchronous in what scenarios.

Here I can figure out an example to identify these two concepts:

1. Synchronous and asynchronous synchronous and asynchronous attention is the message communication mechanism (synchronous communication/asynchronous communication) so-called synchronization, is the issue of a *called* When the result is not obtained, the *called* Will not return. But once the call returns, it gets the return value. In other words, it is by *called by* Actively waiting for this *called* The result. And Async is the opposite, *called* After the issue,This call is returned directly to the, so no results are returned. In other words, when an asynchronous procedure call is made, the caller does not get the result immediately.  Instead, the caller is notified by status, notification, or by a callback function to handle the call after the * call * is issued.  A typical asynchronous programming model is a popular example: you call the bookstore owner there is no "distributed System" this book, if it is a synchronous communication mechanism, the bookstore owner will say, you wait, "I check", and then began to check AH check, and so check (may be 5 seconds, may be a day) to tell you the results (return results). and the asynchronous communication mechanism, the bookstore owner directly told you I check Ah, check the phone to you, and then directly hung up (do not return the results).  And then check it out and he'll call you on his own initiative.  Here the boss calls back by "callback" this way. 2. Blocking and non-blocking blocking and non-blocking concerns the state of the program while it waits for the call result (message, return value). The blocking call means that the current thread is suspended until the call results are returned. The calling thread will not return until the result is obtained. A non-blocking call means that the call does not block the current thread until the result is not immediately available. Or the above example, you call to ask the bookstore owner there is no "distributed System" this book, if you are blocking calls, you will always put yourself "hang" until the book has no results, if the non-blocking call, you don't care if the boss has told you, you have to play the first side, Of course, you'll have to check the boss for a few minutes occasionally. Here the blocking is independent of the non-blocking and whether synchronous asynchronous.  It has nothing to do with how the boss responds to your results. Before we begin to solve the above problems, let's discuss the use of the Callbale interface to create threads.
@FunctionalInterface  Public Interface Callable<v> {    /**     * Returns the result of a task, or throws an exception (if the result cannot     be computed) */     throws Exception;}

The callable interface is a functional interface in which the type of the return value of the call () method is the generic type of the callable interface.  But how does the callable interface relate to threads? The Futuretask class has a constructor that looks like this:

The parameters are formally callable interface objects, and the Futuretask class implements the interface Runnablefuture interface:

 Public class Implements Runnablefuture<v>

Then look at:

 Public Interface extends Runnable, future<v> {        void  run ();}

Finally, the Runnable interface and the future interface are inherited, and in order to illustrate the relationship, we draw the class diagram:

 PackageCom._thread;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.FutureTask; Public classCallablethreadImplementsCallable<string> {    /*** The number of tickets is 50, a total of 100 people to buy tickets*/    Private intTicket = 50;//show the number of tickets@Override PublicString Call ()throwsException { for(inti = 0; I < 100; i++) {            if(Ticket > 0) {System.out.println ("Buy Tickets: Ticket =" + This. ticket--); }        }        return"The tickets are sold out!" "; }     Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {//Create a callable interface object here I created two Task objectsCallable<string> Callable1 =NewCallablethread (); Callable<String> Callable2 =NewCallablethread (); //Store the created callable Task object in the Futuretask objectFuturetask<string> task1=NewFuturetask<string>(CALLABLE1); Futuretask<String> task2=NewFuturetask<string>(Callable2); //Start thread Execution task        NewThread (Task1). Start (); NewThread (Task2). Start (); //The above code is just an execution thread, callable interface can produce results, futuretask can get results//call the Get () method to block the currently executing thread from getting the resultsSYSTEM.OUT.PRINTLN ("Thread A's return result is:" +task1.get ()); System.out.println ("The return result of thread B is:" +task2.get ()); }}

This is an implementation process that uses the callable interface to create threads; Okay, now let's talk about Java asynchronous programming!

The above diagram illustrates a process of buying a book, which in Java can be viewed as a synchronous operation:

 PackageCom._thread; Public classSlowworker { PublicSlowworker () {} Public voiddoWork () {Try{System.out.println ("= = to find books, find books, find books ======"); Thread.Sleep (2000); System.out.println ("= = ok! ======"); } Catch(interruptedexception e) {e.printstacktrace (); }    }     Public Static voidMain (string[] args) {Slowworker worker=NewSlowworker (); //The main thread simulates the person who buys the book, the DoWork () method simulates the bookstore owner's behavior! System.out.println ("Boss, I want to buy books" +Newjava.util.Date ());        Worker.dowork (); System.out.println ("... I can do something when the boss is looking for a book! ...."); System.out.println ("The book has been bought" +Newjava.util.Date ()); System.exit (0); }}

Look at the results of the operation:

Boss, I want to buy books Sun Jan 01:49:35 CST 2018==== Find books, find books, find books ====== = = ok! ======01:49:37 CST 2018

The above operation is indeed a synchronous operation, and the DoWork () method is called after the main thread runs, while the DoWork () method requires hibernation 2s. But the main thread did not continue to execute, but waited, everyone is not feel like doing things very inefficient. In other words, if you buy a book in the bookstore, the boss looking for a day, you will continue to wait?

Next we talk about the Executorservice interface, which can represent a thread pool object, and when the thread is idle it can accept a callable object that is submitted to Executorservice, and when the thread ends, he returns to a future.

 PackageCom._thread;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/*** Asynchronous Programming *@authorGosaint **/ Public classAsynchronousworker { PublicAsynchronousworker () {} Public voiddoWork () {Try{System.out.println ("= = to find books, find books, find books ======"); Thread.Sleep (2000); System.out.println ("= = ok! ======"); } Catch(interruptedexception e) {e.printstacktrace (); }    }     Public Static voidMain (string[] args) {Slowworker worker=NewSlowworker (); //The main thread simulates the person who buys the book, the DoWork () method simulates the bookstore owner's behavior! System.out.println ("Boss, I want to buy books" +Newjava.util.Date ()); //at this point we create a thread pool with a number of 3Executorservice Service = Executors.newfixedthreadpool (3); //there is a thread pool object at this time, the thread pool object commits the task, is a callable interfacefuture<string> future = Service.submit (NewCallable<string>() {@Override PublicString Call ()throwsException {NewAsynchronousworker (). DoWork (); return NULL;        }        }); System.out.println ("... I can do something when the boss is looking for a book! ...."); System.out.println ("Make love to do things!" "); Try {                 //call this method to get the result of the execution of our task, but prevent the main thread from running until a result is obtainedFuture.get (); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); } System.out.println ("The book has been bought" +Newjava.util.Date ()); System.exit (0); }        }

The results of the operation are as follows:

Boss, I want to buy a book Sun Jan 02:16:13 CST 2018 ... I can do something when the boss is looking for a book! .... Sex to do things! = = = Find books, find books, find books ====== = = ok! ====== book bought Sun Jan 02:16:15 CST 2018

The main thread began to run, and then we submitted a book-buying mission to Executorservice, and then we were doing other things. And finally, the future object gets the result from the executorservice to the execution. We call the Get () method to get the result of the execution; if we do not have this call, then it is a parallel computation, then the boss will not find the results of the book immediately return to us;

Thread 2---Async 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.