Thread-per-Message mode (this work is left to you)
When you are very busy, there is a courier downstairs of the company, so you entrust your colleague to help you get your courier so that you can continue to do your job
In Thread-Per-Message mode, the delegate end of the message and the execution end are different threads. The delegate end of the message will tell the execution end thread, and this work will be handed over to you.
Host class:
The class that creates a thread for requests is mainly by opening a new thread, calling the helper handle, and passing the text to be printed.
public class Host {private final Helper helper = new Helper();public void request(final int count,final char c){System.out.println("request start");new Thread(){public void run(){helper.handle(count, c);}}.start();System.out.println("request end");}}Helper class:
Provides character display function, slowly method simulates printing time
public class Helper {public void handle(int count,char c){System.out.println("handle method start");for(int i=0;i<count;i++){slowly();System.out.print(c);}System.out.println("");System.out.println("handle method end");}private void slowly(){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}Main class:
Create an instance of Host and call the request method
public static void main(String[] args) {System.out.println("main begin");Host host = new Host();host.request(10, 'A');host.request(20, 'B');host.request(30, 'C');System.out.println("main End");}Test results:
main begin
The request method has begun
The end of the request method
The request method has begun
The end of the request method
The request method has begun
The end of the request method
main End
Start the handle method
Start the handle method
Start the handle method
BACBACBACBACBACBACBACBACBACBA
End of handle method
CBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCB
End of handle method
CCCCCCCCCCCC
End of handle method
From the results of the operation, we can see that the request method does not wait for the handle method to be executed before execution, but calls the handle method and returns to the request method until the run ends. Therefore, it is equivalent to the request method passing the work of printing a certain number of characters to be performed to the handle method, and the request method can execute other statements in the stupid method without waiting for the handle method to complete. This also tells us that when some work is time-consuming, new threads can be started in this mode to perform processing. This mode can be applied to the server, which can reduce the server's response time.
Explain the process and thread:
The biggest difference between threads and processes is whether memory coexists.
Each process has its own independent memory space. A process cannot read and write the memory of other processes without authorization. Since the memory space of processes is independent of each other, a process does not need to worry about being destroyed by other processes.
Threads can coexist. One thread writes content to the instance, and other threads can read the content of the instance. Since multiple threads can access the same instance, we need to ensure that it performs mutex correctly.
Host design optimization:
1. Design the Host class using the ThreadFactory interface under the java.util.concurrent package
public class Host {public void request(final int count,final char c){System.out.println("request method starts");threadFactory.newThread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubhelper.handle(count, c);} }).start();;System.out.println("request method ends");}}Corresponding Host instantiation object:
Host host = new Host(Executors.defaultThreadFactory());
The advantage of this design is that the original instance code created with new depends on the java.lang.Thread class, and cannot control the part of the creation thread, and is less reusable. If threadFactory is used to save the objects of the corresponding class and call the newThread method to create a new thread, the creation of thread is realized. This no longer depends on the Thread class, but depends on the ThreadFactory object passed in the constructor, which implements the details of controlling the creation of threads.
Redesign the Host class using the java.util.concurrent.Executor interface:
The previous ThreadFactory interface hides the details of thread creation, but does not hide the thread creation operations. If the Executor interface is used, the thread creation operations will also be hidden.
public class Host{private final Helper helper = new Helper();private final Executor executor;public Host(Executor executor){this.executor = executor;}public void request(final int count,final char c){System.out.println("request method has started");executor.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubhelper.handle(count, c);}});System.out.println("request method end");}}Created using java.util.concurrent.ScheduledExecutorService class, which can implement scheduled operation
public class Host{private final Helper helper = new Helper();private final ScheduledExecutorService scheduledExecutorService;public Host(ScheduledExecutorService scheduledExecutorService){this.scheduledExecutorService = scheduledExecutorService;}public void request(final int count,final char c){System.out.println("request method has started");scheduledExecutorService.schedule(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubhelper.handle(count, c);}}, 3L, TimeUnit.SECONDS);System.out.println("request method end");}}Test the main function entry:
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);Host host = new Host(scheduledExecutorService);try {host.request(10, 'A');host.request(20, 'B');host.request(30, 'C');} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally{scheduledExecutorService.shutdown();System.out.println("main End");}Summarize
The client role calls the request method of the Host role, and the actual processing of the request is handed over to the Helper handle for execution. However, if the client calls the handle method directly from the request, it cannot be returned from the handle method until the actual operation is over. This will reduce the response performance of the request. Therefore, the Host role will start a new thread used to process the request from the Client role and let the thread call the handle, so that the thread making the request can immediately return from the handle. This is the Thread-Per-Message mode.