A synchronous
A call is made, and if the caller does not finish processing, the caller waits for the caller to return
For example, A program calls method A, and if method A does not return, the program waits
Two asynchronous
A call is made, and if the called method is not finished, the caller does not wait for it and continues to execute. Then, if the called method is finished, a callback is issued to inform the caller of the result of his execution
For example, if method A does not return, the program does not wait for method A to return, and continues to execute the following logic. During the execution of the following logic, the program will be told by the callback function, what is the result of its execution
Three blocks
It is a headache that the difference between synchronization and blocking is described in various ways on the Internet. Synchronization and blocking are indeed similar in that they both need to wait for the called party to finish executing. The difference is that blocking refers to the state of the thread, while synchronization refers to the whole process, and their concerns are different. The thread may be alive or suspended in a synchronous call. For example, in a synchronous method, the following code is executed. The code waits, but the thread is still alive, not blocking the block
count = 0; boolean flag = true; while(flag){ count ++; if(count == 100){ flag = false; }}Copy the code
Here is a snippet of blocking code
ServerSocket so = new ServerSocket(8080); // Calls to the accept method will be blocked until a new connection is established so.accept();Copy the code
The accept() method blocks, and the thread is suspended while it waits. The chestnut on is part of the BIO operation code.
The obvious drawback is that each connection will block. If you want to improve efficiency, you need to open a Socket connection, which can be handled using the familiar multi-threaded model
This method is somewhat efficient, but it also increases the burden on the CPU, and when large numbers of connections are required, it cannot achieve satisfactory results
Four non-blocking
Non-blocking means that the thread is going to keep running during the call, and it’s not going to hang back and wait, and its implementation actually uses a Selector, so let’s look at a non-blocking design model
All we have to do is open a thread, and then access the completion state of a read or write operation through a Selector poll, which is NIO’s model.